Calculate distance between vectors and generate a distance matrix

3 views (last 30 days)
Hello,
My problem is that I have a file with a collection of features vectors extracted from images and I need to calculate the distances between all the vectors, pair by pair, generating a distance matrix. So, if I have have 100 elements, I need to obtain a 100x100 matrix. Anybody can help me?
Thanks.

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 27 Aug 2013
%Example
v1=randi(10,100,1);
v2=randi(10,100,1);
%--------------------------------
[ii,jj]=ndgrid(v1,v2);
out=reshape(jj(:)-ii(:),100,100);

Matt J
Matt J on 28 Aug 2013
Edited: Matt J on 28 Aug 2013
The advantage of the following is that it uses BSXFUN, avoiding the creation of intermediate matrices. There are also fancier versions on the FEX, e.g.,
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,M]=size(A);
B=reshape(B,N,1,[]);
Graph=l2norm(bsxfun(@minus, A, B),1);
Graph=reshape(Graph,M,[]);
if noself
n=length(Graph);
Graph(linspace(1,n^2,n))=nan;
end
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);

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!