0
votes

I wish to measure the distance of points from the origin(0,0). Based on this question Wrong setting of pdist input data - Matlab I used a loop but I wonder is there another way?

Script:

clc;
clear all;
x1 = [1:11];
y1 = [1;1;11;16;19;3;14;5;16;10;22];
 
x2 = [0];
y2 = [0];
 
  
for i = 1:length(x1)
    dX = [x1(i),y1(i); x2, y2]
    distResult = pdist(dX,'euclidean')
end
1
Use pdist2. No loop required.beaker
Tried this and it is a mess, any simpler solution to find the pairwise distances? x = [flip(rot90(x1)), repmat(0,length(x1),1)]; y = [flip(rot90(x1)), repmat(0,length(y1),1)]; pdist2(x,y,'euclidean')hsi100
Given your point lists as defined above, pdist2([x2, y2], [x1.', y1])beaker

1 Answers

4
votes

If you are just looking for Euclidean distance with a fixed point like the `(0, 0), you can do it without any explicit loop, like the following:

x1 = [1:11].';
y1 = [1;1;11;16;19;3;14;5;16;10;22];
distResults = sqrt(x1.^2 + y1.^2);

Moreover, if you desire to find the distance from a fixed point like (x0, y0) other than the origin, you can do the following:

distResults = sqrt((x1 - x0).^2 + (y1 - y0).^2)

If you have concern of different metrics, you can use pdist2 (as mentioned in comments) like the following:

x1 = [1:11].';
y1 = [1;1;11;16;19;3;14;5;16;10;22];
distResults = pdist2([x1 y1], [0,0], 'euclidean');