Is there a better (faster) way to code this?
Show older comments
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
More Answers (2)
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.
JnLongchamp
on 1 Sep 2015
1 Comment
Star Strider
on 1 Sep 2015
I appended my vectorisation of your code in a Comment to my original Answer.
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!