I have this variable formatted as following:
>> dist
dist =
0 7.5000 15.0000 16.7705 21.2132 16.7705 15.0000 7.5000
7.5000 0 7.5000 10.6066 16.7705 15.0000 16.7705 10.6066
15.0000 7.5000 0 7.5000 15.0000 16.7705 21.2132 16.7705
16.7705 10.6066 7.5000 0 7.5000 10.6066 16.7705 15.0000
21.2132 16.7705 15.0000 7.5000 0 7.5000 15.0000 16.7705
16.7705 15.0000 16.7705 10.6066 7.5000 0 7.5000 10.6066
15.0000 16.7705 21.2132 16.7705 15.0000 7.5000 0 7.5000
7.5000 10.6066 16.7705 15.0000 16.7705 10.6066 7.5000 0
I want to obtain a 8x7 array because I want to eliminate all the 0 element rows by rows. The structure of the files is always the same with the 0 value on the main diagonal. How can I do this?

 Akzeptierte Antwort

Matt Tearle
Matt Tearle am 21 Feb. 2014

1 Stimme

Personally, I'd question whether this is a great idea. A distance matrix is supposed to be square and symmetric, with dist(j,k) representing the distance between points j and k. Removing those diagonal elements destroys that structure, and I don't see what it gains you. But if there's a good reason to go ahead, you could do:
n = size(dist,1);
dist(1:(n+1):end) = [];
dist = reshape(dist,n-1,n);

4 Kommentare

Walter Roberson
Walter Roberson am 21 Feb. 2014
I thought of that, but this would not shift the elements left to fill the gap.
Deleting the 0 diagonal can be useful when finding nearest neighbours from a distance matrix, as you do not want the min() to be matching the 0 of the distance to itself.
Francesco
Francesco am 21 Feb. 2014
Your previous code is very awesome. I have to test it with another configuration. I do not know how you've been able to do so. Now that I think about it I wonder you did not need the line of code that calculate the distance between the points? It's not useful for your code?
@Walter: true, I shifted down instead of across. Add a transpose, I guess :) The 0 on the diagonal is a good point. But in that case, my personal preference would be to fill the diagonal with NaNs:
n = size(dist,1);
dist(1:(n+1):end) = NaN
min(dist)
(But I guess there are other cases where that would be annoying, too...)
@Francesco: I've added a comment on that other question about how my code works. But, no, I don't use the distances for that.
That said, if you find pairwise distances to be useful, and you have Statistics Toolbox, there's a function to do it for you: pdist. If you want the matrix form, use squareform as well:
coords = rand(8,2); % column 1 is x, column 2 is y
dist = squareform(pdist(coords));
Francesco
Francesco am 22 Feb. 2014
Matt the problem is that I want to obtain a 8x7 matrix. I have to eliminate the zero element rows by rows.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Chad Greene
Chad Greene am 21 Feb. 2014

0 Stimmen

dist2 = repmat(dist(~eye(size(dist))),1,7)

Kategorien

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by