MATLAB: Vectorization of this loop

memoryvectorizationvectorizing

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

Best Answer

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);
Related Question