how i can vectorize this code using bsxfun or meshgrid?

Hi,
I am trying to vectorize this code, but I dont know how to start it, I read the help files for both bsxfun and meshgrid but no luck. Can someone please guide how to look at this rather than giving the code. My code is working for me but i want to improve it.
s1= 50;
s2=100;
E_=zeros(s2,s2);
grid_=linspace(-2.5,2.5,s2);
tau=linspace(-pi,pi,s1);
x=cos(tau);
y=sin(tau);
cur=myfun(x,y); %returns vector
for k=1:s2
for m=1:s2
for n=1:s1
R= abs(sqrt((grid_(m)-x(n))^2+(grid_(k)-y(n))^2));
u_(n)= besselj(0,R)*cur(n);
end
E_(k,m)=abs(trapz(tau,u_));
end
end
Thanks
Turker

 Respuesta aceptada

Jan
Jan el 14 de Mzo. de 2017
Editada: Jan el 15 de Mzo. de 2017
You can replace the inner loop by:
R = abs(sqrt((grid_(m)-x) .^ 2 + (grid_(k)-y) .^ 2)); % [EDITED]: ^ to .^
u_ = besselj(0, R) .* cur;
I guess, that the abs() is not required.

4 comentarios

ttopal
ttopal el 15 de Mzo. de 2017
Thanks Jan, x and y are array. And I a calculating the distance between points one by one. When we change it like this, does R become an array?
Jan
Jan el 15 de Mzo. de 2017
Editada: Jan el 15 de Mzo. de 2017
Yes, R has the same size as x and y, and u_ has also. At least if you run the improved version which uses the elementwise squaring .^2. See [EDITED]
Hi Jan, it returns error as;
Assignment has more non-singleton rhs dimensions than
non-singleton subscripts
Error in testfields (line 121)
E_(k,m)=abs(trapz(tau,u_));
ttopal
ttopal el 16 de Mzo. de 2017
Editada: ttopal el 16 de Mzo. de 2017
R = abs(sqrt((grid_(m)-x) .^ 2 + (grid_(k)-y) .^ 2))'; %transpoze added.
u_ = besselj(0, R) .* cur;
Now it works! Thank you Jan!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 14 de Mzo. de 2017

Editada:

el 16 de Mzo. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by