필터 지우기
필터 지우기

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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by