I am writing a program for school, and I have nested loops that create a 4-dimensional array (the distances between two points with coordinates (x, y) and (x ', y')), as shown below
pos_x=1:20;
pos_y=1:20;
Lx = length(pos_x);
Ly = length(pos_y);
Lx2 = Lx/2;
Ly2 = Ly/2;
%Distance function, periodic boundary conditions
d_x=abs(repmat(1:Lx,Lx,1)-repmat((1:Lx)',1,Lx));
d_x(d_x>Lx2)=Lx-d_x(d_x>Lx2);
d_y=abs(repmat(1:Ly,Ly,1)-repmat((1:Ly)',1,Ly));
d_y(d_y>Ly2)=Ly-d_y(d_y>Ly2);
for l=1:Ly
for k=1:Lx
for j=1:Ly
for i=1:Lx
distance(l,k,j,i)=sqrt(d_x(k,i).^2+d_y(l,j).^2);
end
end
end
end
d_x and d_y are only 20x20 matrices and Lx = Ly for trial purposes. This is a very slow and obviously not very elegant way to do this. I tried to vectorize the nested loops and was able to get rid of the two inner loops as:
dx2=zeros(Ly,Lx,Ly,Lx);
dy2=zeros(Ly,Lx,Ly,Lx);
distance=zeros(Ly,Lx,Ly,Lx);
for l=1:Ly
for k=1:Lx
dy2(l,k,:,:)=repmat(d_y(l,:),Ly,1);
dx2(l,k,:,:)=repmat(d_x(k,:)',1,Lx);
end
end
distance=sqrt(dx2.^2+dy2.^2);
which basically replaces the above 4 loops. I tried for 2 days, but could not find a way to vectorize all the loops. I wanted to ask:
- Is it possible to get rid of these two cycles at all?
- , .
repmat 4 , 4- , .
.
. , , , x-y. , . x ay, osci(1,1) osci(1,1),..osci(1,N),osci(2,1),..osci(N,N)..., osci(1,2) osci(1,1)...osci(N,N) .. ( ), , 4-D , .