Need help to vectorize this small code

Hi,
i would need help to vectorize this short code:
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
l and pi are numbers. thanks a lot in advance!!
best

回答 (2 件)

Guillaume
Guillaume 2015 年 12 月 8 日
編集済み: Guillaume 2015 年 12 月 8 日

0 投票

[u, v] = ndgrid(1-N/2:N/2);
cube = u.^2 + v.^2;
S = exp(1i*pi*l*cube)

1 件のコメント

Jean-Nicolas Longchamp
Jean-Nicolas Longchamp 2015 年 12 月 8 日
Thanks a lot!
Jan
Jan 2015 年 12 月 8 日

0 投票

I assume your want to vectorize the code to increase the processing speed. In your example the exp() function is more expensive than the loops. You can reduce the number of exp calls:
u = (1-N/2):(N/2);
expU = exp(i * pi * l * u.^2);
S = bsxfun(@times, expU, expU.');

1 件のコメント

Jean-Nicolas Longchamp
Jean-Nicolas Longchamp 2015 年 12 月 8 日
Perfect thanks!
Is there a way to further accelerate the computation of exp() in Matlab?

この質問は閉じられています。

タグ

質問済み:

2015 年 12 月 8 日

閉鎖済み:

2021 年 8 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by