フィルターのクリア

Vectorization of this loop

2 ビュー (過去 30 日間)
Dilunath Hareendranath
Dilunath Hareendranath 2012 年 4 月 18 日
The following loop calculates the distance and angle values of every location from a point and stores in arrays named Radius and theta. This loop is called nearly 3600 times in the code. This loop is effecting the performance of the code. Please suggest some ways to vectorise this loop.
xwidth and ywidth varies from 500 to 750. So, memory needed is also very high. Please suggest ways to decrease the memory needed.
x1=0;
y1=1;
inj_x=round(xwidth/2.0);
inj_y=round(ywidth/2.0);
Radius=zeros(ywidth,xwidth);
theta=zeros(ywidth,xwidth);
for r=1:ywidth
for c=1:xwidth
x2=r-inj_y;
y2=c-inj_x;
Radius(r,c)=(x2^2+y2^2)^.5;
theta(r,c)=mod(atan2(x1*y2-x2*y1,x1*x2+y1*y2),2*pi);
end
end
Thanks in advance

採用された回答

Andrei Bobrov
Andrei Bobrov 2012 年 4 月 18 日
in your case
r = (1:ywidth).' - round(ywidth/2);
c = (1:xwidth) - round(xwidth/2);
Radius = bsxfun(@hypot,r,c);
theta = mod(bsxfun(@atan2,-r,c),2*pi);
  1 件のコメント
Dilunath Hareendranath
Dilunath Hareendranath 2012 年 4 月 18 日
Thanks andrei.. This code is taking only 0.09 seconds to process.. whereas previous code was taking 2.8 seconds.

サインインしてコメントする。

その他の回答 (2 件)

Honglei Chen
Honglei Chen 2012 年 4 月 18 日
x1=0;
y1=1;
inj_x=round(xwidth/2.0);
inj_y=round(ywidth/2.0);
[x2,y2] = ndgrid((1:ywidth)'-inj_y,(1:xwidth)'-inj_x);
Radius=(x2.^2+y2.^2).^.5;
theta=mod(atan2(x1.*y2-x2.*y1,x1.*x2+y1.*y2),2*pi);
  1 件のコメント
Dilunath Hareendranath
Dilunath Hareendranath 2012 年 4 月 18 日
Thanks Honglei Chen for answering. This code is also taking less time.

サインインしてコメントする。


Jan
Jan 2012 年 4 月 18 日
For a fair speed comparison cleanup the loops:
  • move all repeated calculation outside
  • SSQRT() is faster than ^0.5
twoPi = 2 * pi;
for r = 1:ywidth
x2 = r - inj_y;
x2_2 = x2 * x2;
x1x2 = x1 * x2;
y1x2 = y1 * x2;
for c = 1:xwidth
y2 = c-inj_x;
Radius(r,c) = sqrt(x2_2 + y2^2);
theta(r,c) = mod(atan2(x1*y2 - y1x2, x1x2 + y1*y2), twoPi);
end
end
Perhaps a partial vectorization is fastest:
twoPi = 2*pi;
for c = 1:xwidth
y2 = c-inj_x;
x2 = transpose(1-inj_y:ywidth - inj_y);
Radius(:,c) = sqrt(x2.^2 + y2^2);
theta(:,c) = mod(atan2(x1*y2-x2*y1, x1*x2+y1*y2), twoPi);
end
And fully vectorized:
x2 = transpose(1 - inj_y:ywidth - inj_y);
y2 = 1 - inj_x:xwidth - inj_x;
Radius = sqrt(bsxfun(@plus, x2 .^ 2 + y2 .^ 2);
k1 = bsxfun(@minus, x1 * y2, y1 * x2);
k2 = bsxfun(@plus, x1 * x2, y1 * y2);
theta = mod(bsxfun(@atan, k1, k2), 2*pi);
And if x1 and y1 are really fixed to 0 and 1 this can be simplified.
  1 件のコメント
Dilunath Hareendranath
Dilunath Hareendranath 2012 年 4 月 18 日
Thanks Jan Simon for giving many ways to do the job.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by