Avoiding for loops problem
조회 수: 5 (최근 30일)
이전 댓글 표시
What I want to do is the following:
Given a matrix A of size [M,N] (rows are vectors) and another matrix B of size [Q,N] (rows are vectors) I want to construct a matrix with the squared distance between each vector of A with all the vectors of B and put it in matrix D. So D(i,j) = sum(((A(i,:)-B(j,:)).^2)
I want to avoid using a double for loop over i and j for creating this because I want to speed up the process. If matrix A would be of size [1,N] I'd think I could transform it into a matrix C of size [Q,N] with on every row the same vector and just go D = sum((C-A).^2) . I'm not sure if this would be a good idea and then I'd still need a for loop to go over the other vectors if A wasn't a [1,N] matrix.
Is there any logical solution or should I just stick to for loops?
댓글 수: 0
답변 (4개)
Teja Muppirala
2013년 2월 27일
If you have the Statistics Toolbox, you can use the PDIST2 function. It is very fast.
A = rand(200,100);
B = rand(300,100);
pdist2(A,B).^2
댓글 수: 0
Matt J
2013년 2월 26일
There are also some generalizations of this capability on the FEX, e.g.,
댓글 수: 0
Matt J
2013년 2월 26일
If you organize your vectors column-wise instead of row-wise, you can do this without PERMUTE operations, using the utility below. Permute operations are slow.
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;
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!