Vectorization of this loop
조회 수: 1 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
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);
추가 답변 (2개)
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);
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!