Path: news.mathworks.com!not-for-mail
From: "John D'Errico" <woodchips@rochester.rr.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: euclidean distance
Date: Tue, 30 Jun 2009 22:53:01 +0000 (UTC)
Organization: John D'Errico (1-3LEW5R)
Lines: 27
Message-ID: <h2e50d$pot$1@fred.mathworks.com>
References: <h2dp5l$p98$1@fred.mathworks.com>
Reply-To: "John D'Errico" <woodchips@rochester.rr.com>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1246402381 26397 172.30.248.38 (30 Jun 2009 22:53:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 30 Jun 2009 22:53:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 869215
Xref: news.mathworks.com comp.soft-sys.matlab:551859


"kudrah " <elzarogia@yahoo.gr> wrote in message <h2dp5l$p98$1@fred.mathworks.com>...
> 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
> 
> Thank you in advance!!!!

This matrix will take roughly 300 megabytes to store.
This is one reason why it takes forever. A bigger reason
for the slowness is that you failed to preallocate the
memory.

Finally, you might convert to single precision to store
the distances, so this might work best:

D = bsxfun(@times,single(A(:,1)),single(B(:,1)).');
D = D + bsxfun(@times,single(A(:,2)),single(B(:,2)).');
D = D + bsxfun(@times,single(A(:,3)),single(B(:,3)).');
D = sqrt(D);

HTH,
John