Simplifying the use of meshgrid in Matlab

2019-07-18 02:27发布

Background

Expanding upon this question. I have a collection of points (in a three axes system, so with (x,y,z) coordinates), and i want to calculate the distance between each point.

For that i first have to make a matrix with all possible combinations of points (preferably without duplicates, to save on processing time), to then calculate all the distances.

Problem

Now I am trying to use meshgrid for this, but it's getting pretty complicated. It's getting complicated because the (x,y,z) coordinates are in a matrix that is formatted as: pointCoordinates[x,y,z,pointnumber]

And i don't know how to tell meshgrid to just combine point-1 and point-2 etc., without also combining all the separate x-coordinates with all the separate y-coordinates, etc. (wich are far too many combinations, most of which are useless).

Question

How do i keep meshgrid from making redundant combinations of coordinates? Or is there a simpler way to do this?


I guess i could reformat the pointCoordinates matrix to a simple string array points (with as many entries as there are coordinates). Where entry one is (1,3,5), entry two (2,4,2), etc. Thereby keeping the coordinates together, and limiting the number of possible combinations. But that seems redundant.

2条回答
乱世女痞
2楼-- · 2019-07-18 02:38

You can create 3 meshgrids, for x,y and z.

 x = pointCoordinates(:,1);
 y = pointCoordinates(:,2);
 z = pointCoordinates(:,3);

 [X1,X2] = meshgrid(x,x);
 [Y1,Y2] = meshgrid(y,y);
 [Z1,Z2] = meshgrid(z,z);

Then compute the distance for each one:

 (X1-X2).^2 + (Y1-Y2).^2 + (Z1-Z2).^2;

Now, you need to extract the lower diagonal part, since there are duplications.

查看更多
Anthone
3楼-- · 2019-07-18 02:46

There is indeed a simpler way. If you only want to calculate non-redundant points, you can use pdist. Note that you can choose a different distance metric than Euclidean.

distances = pdist(pointCoordinates(:,1:3));

From the help:

The output D is arranged in the order of ((2,1),(3,1),..., (m,1),(3,2),...(m,2),.....(m,m–1)), i.e. the lower left triangle of the full m-by-m distance matrix in column order. To get the distance between the ith and jth observations (i < j), either use the formula D((i–1)*(m–i/2)+j–i), or use the helper function Z = squareform(D), which returns an m-by-m square symmetric matrix, with the (i,j) entry equal to distance between observation i and observation j.

查看更多
登录 后发表回答