Path: news.mathworks.com!not-for-mail
From: Peter Perkins <Peter.Perkins@MathRemoveThisWorks.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: euclidean distance
Date: Wed, 01 Jul 2009 10:25:26 -0400
Organization: The MathWorks, Inc.
Lines: 22
Message-ID: <h2frkm$kb6$1@fred.mathworks.com>
References: <h2dp5l$p98$1@fred.mathworks.com>
NNTP-Posting-Host: perkinsp.dhcp.mathworks.com
Mime-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 7bit
X-Trace: fred.mathworks.com 1246458326 20838 172.31.57.88 (1 Jul 2009 14:25:26 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 1 Jul 2009 14:25:26 +0000 (UTC)
User-Agent: Thunderbird 2.0.0.22 (Windows/20090605)
In-Reply-To: <h2dp5l$p98$1@fred.mathworks.com>
Xref: news.mathworks.com comp.soft-sys.matlab:552019


kudrah wrote:
> Hi everyone!
> Im trying to calculate the euclidean distance between 2 matrices that contain 3d points.The matrices are quite large,eg A=19500x3 and B=2000x3.I want to calculate the distance between each point of A to each point of B and thus produce a 19500x2000 matrix.So far i wrote this but it takes like forever..Is there any faster way???
> 
> for i=1:size(A,1);
>     for k=1:size(B,1);
> Eucl_Ideal(i,k)=norm(A(i,:)-B(k,:));
>     end 
> end

As others have said, preallocate the result.  Also:

Because of the way data is stored in MATLAB, your loops are in the wrong order -- you want to have the row index in Eucl_Ideal varying fastest or you will be accessing memory very non-sequentially.

But most likely, you want to loop over 1:3 within 1:2000, and sum the squared diffs for each dimension of each point in B to all points in A, vectorized.  This is essentially what John suggested with BSXFUN (though I think those ought to be @minus's, wrapped in .^2's).  Here's an "unrolled loop" version.

Eucl_Ideal = zeros(size(A,1),size(B,1));
for i = 1:size(B,1);
    Eucl_Ideal(:,i) = sqrt((A(:,1)-B(i,1)).^2 + (A(:,2)-B(i,2)).^2 + (A(:,3)-B(i,3)).^2);
end

There's a good deal that can be learned about memory access and vectorization from this example.  Hope this helps.