# Help needed to decrease computational time by removing for loops

2 views (last 30 days)
Nikhil on 1 Mar 2018
Hello Everyone, I have written following 40 lines of matlab code. It is working fine. Only problem is computational costs is very high for nx=1024 and ny=1024 number of points. I believe it is because of the multiple for loops that I have used. Can anybody please suggest me better coding practice to minimize computational time for this code when nx=1024?
tic
nx=512+1;
ny=nx;
dx=(2-(-2))/(nx-1);
dy=dx;
x=-2:dx:2;
y=-2:dy:2;
[Y,X]=meshgrid(x,y);
A=ones(nx,ny);
P=sqrt(A-X.^2-Y.^2);
P=real(P);
Hact=zeros(nx,ny);
error=0;
for i=1:1:(length(X)+1)/2
for j=1:1:(length(Y)+1)/2
Xp=X+(-X(i,j)+dx/2)*A;
Yp=Y+(-Y(i,j)+dy/2)*A;
Xm=X+(-X(i,j)-dx/2)*A;
Ym=Y+(-Y(i,j)-dy/2)*A;
E1=(Xp).*log((Yp+sqrt(Yp.^2+Xp.^2))./(Ym+sqrt(Ym.^2+Xp.^2)));
E2=(Xm).*log((Ym+sqrt(Ym.^2+Xm.^2))./(Yp+sqrt(Yp.^2+Xm.^2)));
E3=(Yp).*log((Xp+sqrt(Xp.^2+Yp.^2))./(Xm+sqrt(Xm.^2+Yp.^2)));
E4=(Ym).*log((Xm+sqrt(Ym.^2+Xm.^2))./(Xp+sqrt(Xp.^2+Ym.^2)));
K=(2/pi^2)*(E1+E2+E3+E4);
G(i,j)=sum(sum(K.*P));
end
end
et=toc;
I1=G(:,1:end-1);
I1=fliplr(I1);
I2=G(1:end-1,:);
I2=flipud(I2);
I3=G(1:end-1,1:end-1);
I3=rot90(I3,2);
D=[G I1;I2 I3];
Ho=(-1)*A;
H=Ho+0.5*X.^2+0.5*Y.^2+D;
for i=1:1:nx
for j=1:1:ny
if (X(i,j)^2+Y(i,j)^2 <= 1)
error=error+dx*dy*abs(H(i,j)-0);
end
end
end

Seyedali Mirjalili on 2 Mar 2018
You can use the concept of vectorization. Here is an example:
With for loop:
for k = 1 : 10
a(k) = k ^ 2;
end
Vectorized version:
k = 1 : 10;
a = k .^ 2
Good luck

Seyedali Mirjalili on 2 Mar 2018
By the way, if you want to check the speed, just write:
tic
// code fragment for either for loop of vectoriaed version.
toc