Is there a better (faster) way to code this?

Hi,
i am doing some matrix manipulation on quite big arrays (up to 4000x4000 elements). I am trying to find the best way to code the following:
for k=1:N
for w=1:N
u=(k-(N/2)); v=(w-(N/2));
cube=(u^2+v^2);
S(k,w)=exp(i*pi*l*cube);
end
end
Do you have any suggestions?
Thanks a lot in advance!

 Accepted Answer

I don’t know what ‘l’ is so I can’t run your code.
I would avoid the loop and use meshgrid:
[U,V] = meshgrid(-N/2:N/2);
cube=(U.^2+V.^2);
S = exp(1i*pi.*l.*cube);

1 Comment

Vectorising your loop using my approach is relatively straightforward:
eta=1000;
omega=30;
pi=3.14;
N=4000;
APO=zeros(N);
[X,Y] = ndgrid(-N/2:N/2);
rho = hypot(X,Y);
APO=(cos((pi/(2*omega)*((rho-eta))))).^2;
APO(rho<eta) = 1;
APO(rho>(eta+omega)) = 0;
I checked this (and plotted it with N = 400 and eta = 100) and it gives the same results as the loop version. It’s significantly faster.

Sign in to comment.

More Answers (2)

Stephen23
Stephen23 on 18 Aug 2015
Edited: Stephen23 on 27 Aug 2015
You could simply use vectorized code:
l = 2;
N = 3;
V = ((1:N)-N/2).^2;
T = bsxfun(@plus,V,V(:));
T = exp(i*pi*l*T);
Writing vectorized code is often much faster and more efficient than using loops, because it works on complete arrays, not single elements. If you want to use MATLAB effectively then you need to learn how to write vectorized code and leave those loops for the poor low-level languages.
However if you do need to assign to an array in a loop you should always preallocate the array before the loop, as this makes a big difference to MATLAB's performance.
Thanks a lot for your responses! Helped already a lot. Now i am trying to vectorize the following loop but not succeeded yet. Do you have any suggestions?
eta=1000;
omega=30;
pi=3.14;
N=4000;
APO=zeros(N);
for r=1:N
for s=1:N
x=r-(N/2);
y=s-(N/2);
rho=sqrt(x^2+y^2);
if rho<eta
APO(r,s)=1;
elseif rho>(eta+omega)
APO(r,s)=0;
else
APO(r,s)=(cos((pi/(2*omega)*((rho-eta)))))^2;
end
end
end

1 Comment

I appended my vectorisation of your code in a Comment to my original Answer.

Sign in to comment.

Categories

Community Treasure Hunt

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

Start Hunting!