Hi all,
I have the following code:
for i=1:1:length(y)
for j=1:1:length(x)
if ((X(i,j))^2)/(R_ell^2) + ((Y(i,j))^2)/(r_ell^2) < 1.0
Z(i,j)=0.0;
end
end
end
It takes a lot of time. Can someone help me t speed up these loops?
Thank you

 Respuesta aceptada

Star Strider
Star Strider el 2 de Nov. de 2019

0 votos

I am not certain what you are doing or what the values of the vectors and ‘r_ell’ are. Use ndgrid and vectorisation to make this a fast, straightforward calculation:
x = linspace(-10, 10, 15); % Guessing Values
y = linspace(-10, 10, 11); % Guessing Values
[X,Y] = ndgrid(x, y);
r_ell = 4.2; % Guessing Value, Assuming Scalar
Z = (X.^2 + Y.^2)./(r_ell.^2);
Z(Z<1) = 0;
Supply the correct values for the vectors and ‘r_ell’.

2 comentarios

Hi Star Strider,
thank you very much! It works:)
Do you know any way for speeding up also the following code?
eq_green = (x-xC_green)^2 + (y-yC_green)^2 - r_green^2 == 0.0;
eq_red = (x-xC_red)^2 + (y-yC_red)^2 - r_red^2 == 0.0;
eq1 = x <= 0.0;
eq2 = y <= 0.0;
eqns = [eq_green, eq_red,eq1,eq2];
vars = [x y];
S = solve(eqns, vars);
Star Strider
Star Strider el 3 de Nov. de 2019
As always, my pleasure!
I do not follow what you are doing with the code in your Comment. However rather than use the Symbolic Math Toolbox (that is good for derivations and expression simplifications although not suited for repetitive calculations), using the Optimization Toolbox fsolve function is likely more efficient. Note that it will not solve for both roots of the quadratic functions simultaneously, and you will need to give it imaginary or complex initial estimates to have it solve for imaginary or complex results, so separate runs with different initial estimates will quite likely be necessary.
To use fsolve, experiment with something like this:
Eqns = @(b,xC_green,yC_green,xC_red,yC_red) [(b(1)-xC_green)^2 + (b(2)-yC_green)^2 - r_green^2; (b(1)-xC_red)^2 + (b(2)-yC_red)^2 - r_red^2];
B = fsolve(@(b)Eqns(b,xC_green,yC_green,xC_red,yC_red), -ones(1,2))
I have no idea what the constants are so I cannot test this. Consider it UNTESTED CODE.
Experiment to get the results you want.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Etiquetas

Preguntada:

el 2 de Nov. de 2019

Comentada:

el 3 de Nov. de 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by