continuous search of the closest rows in a matrix
조회 수: 2 (최근 30일)
이전 댓글 표시
Hello,
Consider a 100x10 matrix and a random row of it, let be "row1".
I want to calculate the Euclidean distance between "row1" and the rest of the rows and I want to find the closest row to "row1", let be "row2".
Then I want to find the closest row to "row2", let be "row3" (the "row1" has been excluded from the matrix) and so on.
I use the "pdist2" for the Euclidean distance.
How you please help me?
Thank you.
Best,
Pavlos
댓글 수: 4
채택된 답변
Matt J
2013년 1월 15일
편집: Matt J
2013년 1월 15일
Here's what I use. There are others like it on the FEX, some of them fancier.
function Graph=interdists(A,B)
%Finds the graph of distances between point coordinates
%
% (1) Graph=interdists(A,B)
%
% in:
%
% A: matrix whose columns are coordinates of points, for example
% [[x1;y1;z1], [x2;y2;z2] ,..., [xM;yM;zM]]
% but the columns may be points in a space of any dimension, not just 3D.
%
% B: A second matrix whose columns are coordinates of points in the same
% Euclidean space. Default B=A.
%
%
% out:
%
% Graph: The MxN matrix of separation distances in l2 norm between the coordinates.
% Namely, Graph(i,j) will be the distance between A(:,i) and B(:,j).
%
%
% (2) interdists(A,'noself') is the same as interdists(A), except the output
% diagonals will be NaN instead of zero. Hence, for example, operations
% like min(interdists(A,'noself')) will ignore self-distances.
%
% See also getgraph
noself=false;
if nargin<2
B=A;
elseif ischar(B)&&strcmpi(B,'noself')
noself=true;
B=A;
end
N=size(A,1);
B=reshape(B,N,1,[]);
Graph=l2norm(bsxfun(@minus, A, B),1);
Graph=squeeze(Graph);
if noself
n=length(Graph);
Graph(linspace(1,n^2,n))=nan;
댓글 수: 7
추가 답변 (1개)
Teja Muppirala
2013년 1월 16일
If you have the Statistics Toolbox installed, instead of using PDIST2, use PDIST (along with SQUAREFORM) instead. It is designed to find all interpoint distances for a single matrix very efficiently. Then your entire problem could be reduced to this:
M = randn(100,10);
L = size(R,1);
D = squareform(pdist(M));
D(1:L+1:L^2) = nan;
startrow = 1; % Starting Row
row = [startrow; zeros(L-1,1)];
for n = 2:L
oldrow = startrow;
[val,startrow] = min(D(:,startrow));
D(oldrow,:) = nan;
row(n) = startrow;
end
row
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!