Compute,store, and find min of 3d distances between two different matrices.

5 views (last 30 days)
Hello, I have trouble using the built in functions of matlab to do this because what I want is different from what I think those functions do. I have two matrices of 3d points, say A and B. They do not have the same number than elements A<<B. I want to compute distances between each point in A and all points in B, and then be able to store it with the distance and index of the point in B. Then repeat for the next point in A until the end. I was thinking to try to use nested loops reiterating through A and the inner one through B, I just am unsure how to finely put the storage of the distance and index of the min into another vector or matrix (size A x 1)

Accepted Answer

Matt J
Matt J on 16 Aug 2013
Edited: Matt J on 16 Aug 2013
Here's what I use, but there are better optimized alternatives on the FEX.
[distances,index]=min(interdists(A,B),[],2);
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=permute(Graph,[2,3,1]);
if noself
n=length(Graph);
Graph(linspace(1,n^2,n))=nan;
function out=l2norm(X,varargin)
%out=l2norm(X,varargin)
%
%Takes the L2 norm along desired dimensions of the array X.
%
%VARARGIN can be any of the additional arguments of the sum.m function
%and follows the same conventions as this and similar functions. That is,
%if VARARGIN={}, the function operates along the first non-singleton
%dimension, etc...
%
%SEE ALSO sumsq
X=X.^2;
out=sum(X,varargin{:});
out=sqrt(out);

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 16 Aug 2013
A=randi(100,2,2,3)
B=randi(100,2,2,3)
D=sqrt(sum((A-B).^2,3))

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!