Vectorization of 4 nested loops in Matlab

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 , .

+3
2

, , :

enter image description here

1 1 100, 2 1 100 .. , , 1 100, - 1 100.

%# create 100 evenly spaced oscillators
[xOscillator,yOscillator] = ndgrid(1:10,1:10); 
oscillatorXY = [xOscillator(:),yOscillator(:)];

%# calculate the euclidean distance between the oscillators
xDistance = abs(bsxfun(@minus,oscillatorXY(:,1),oscillatorXY(:,1)')); %'# abs distance x
xDistance(xDistance>5) = 10-xDistance; %# add periodic boundary conditions
yDistance = abs(bsxfun(@minus,oscillatorXY(:,2),oscillatorXY(:,2)')); %'# abs distance y
yDistance(yDistance>5) = 10-yDistance; %# add periodic boundary conditions

%# and we get the Euclidean distance
euclideanDistance = sqrt(xDistance.^2 + yDistance.^2);
+1

, , . (.. X Y, Y X),

x = 1:20;
y = 1:20;
[X,Y] = meshgrid(x,y);
Z =X + Y*i;
z = Z(:);
leng = length(z);
store = zeros(leng);
for looper = 1:(leng-1) 
    dummyz = circshift(z,looper);
    store(:,looper+1) = z - dummyz;
end
final = abs(store);
0

All Articles