Search code examples
matlablistrandomcoordinatespoints

store 3d coordinates in a list of points Matlab


I currently face a problem as mentioned in title. If I just want to have 3 separate points and record them as a point with 3 coordinates in matlab is easy like below

A=[0 0 1];%coordinates of Q1
B=[0 0 -1];%coordinates of Q2
C=[0 1 0];%coordinates of Q3

Therefore, that describes the coordinates of A(0,0,1), B(0,0,-1), C(0,1,0). In the further calculation, I could use the coordinate and do the computation like:

R1=A-B; %vector from Q2 to Q1
R2=A-C; %vector from Q3 to Q1
R3=C-B; %vector from Q2 to Q3

However, if I want to generate many points like randomly with 100 points, the way I am writing above is stupid. And I also want to use the coordinates to do it as before since it is more convenient. Below is the method I have tried.

% random distributed points
x = rand(Number_of_Points, 1);
y = rand(Number_of_Points, 1);
z = x.^2 + y.^2;

Points = [x(:) y(:) z(:)];

But it just record 3 coordinates of all the points I couldn't record them separately as I did it before. I want to calculate the vector by using Points(1)-Points(2) Does any one have idea how to do it?


Solution

  • You just need to use subscript indexing instead of linear indexing:

    Points(1,:) - Points(2,:)
    

    or else if you wanted Euclidean distance you can do it like

     sqrt(sum((Points(1,:) - Points(2,:)).^2))
    

    or make yourself an anonymous function:

    PointsDistance = @(a,b)(sqrt(sum((Points(a,:) - Points(b,:)).^2)))
    

    and now you can call

    PointsDistance(1,2)