Search code examples
arraysmatlabmatrixdistance

How to calculate distance between some randomly generated matrix and a given array in matlab


Here in this code, 50 random coordinates are generated(population size 50). I have an array,

B = [150 90; -100 -120; -80 130; 140 -70; 60 120; -90 -130].

I want to calculate the distance of each 50 coordinates from each of the coordinates of B array. After calculating the distance, I have to preserve all of the distance values separately in an array(or matrix) to retrieve them afterwards. Please help me to calculate the distance.

clear all
clc

%Common Parameter Setting
N=2;        % Number of variables
M=50;       % Populations size 50
F=0.5;      % Mutation factor
C=0.9;      % Crossover rate
I_max=20;   % Max iteration time
Run=1;      % The number of test time
X_max=[100,100];
X_min=[-100,-100];

%Func=@Rastrigin;

% 2.The whole test loop
for r=1:Run
    iter=0;
    % 1.Generate MxN matrix
    for m=1:M
        for n=1:N
            X(m,n)=X_min(n)+rand()*(X_max(n)-X_min(n));
        end
        fprintf('value of X:');
        disp(X);
    end
end

Solution

  • I did not completely understand the last part. But if you have 2 lists of coordinates, say

    x = randn(10,2); %10 points in 2D
    y = randn(3,2); % 3 others points in 2D
    

    and you want the pairwise distance between all points in x and all points in y, you can use pdist2

    D = pdist2(x,y);
    

    Now D(1,2) will be the Euclidean distance from x(1) to y(2) and so on.