Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Minimum distances of one vector to another
Date: Mon, 26 Jan 2009 17:55:03 +0000 (UTC)
Organization: FZ-Juelich
Lines: 63
Message-ID: <glktdn$ok0$1@fred.mathworks.com>
References: <glkphu$6v$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1232992503 25216 172.30.248.35 (26 Jan 2009 17:55:03 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 26 Jan 2009 17:55:03 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1088664
Xref: news.mathworks.com comp.soft-sys.matlab:514013

"Robert Kirdeikis" <kirdeiki@ualberta.ca> wrote in message <glkphu$6v$1@fred.mathworks.com>...
> Hi, i have a program that collapses a sphere onto a body, the program works well but my next step is finding the furthest point away from the body to determine the error. the method i got in there is
> 
>     j=2562
>     win=zeros(m,1);
>     for j=1:m
>         win(j)=min(sqrt(sum(bsxfun(@minus,data,sdata(j,:)).^2,2)));
>     end
>     max(win)
> 
> where sdata is a 2562X3 matrix and  data is a 52000X3 matrix. This program finds the minimum for every row of sdata and stores it in win then finds the maximum distance away from the body. This works okay but the for loop slows down my program by quite a bit and i am looking for suggestions on how to make my program more efficient. Any help would be appreciated and thanks in advance.

Hi Robert,

bsxfun seems to allocate memory on order to calculate then with two matrices of equal size.
My test :
clc
A = magic(1000);
m = mean(A);
tic
for n = 1:20
    AA = bsxfun(@minus, A, m);
end
toc

tic
for n = 1:20
    for n = size(m, 2):-1:1
        AA2(:,n) = A(:,n)- m(n);
    end
end
toc

if you loop twice this should prevent unnecessary allocation

 j=2562
win=zeros(m,1);
for j=1:m

    win(j)=min(sqrt(sum(bsxfun(@minus,data,sdata(j,:)).^2,2)));
end
max(win)

gives
Elapsed time is 0.196413 seconds.
Elapsed time is 0.123616 seconds.

with Walters hint this looks rather like

 j=2562
win=zeros(m,1);
for j=1:m
    for n = size(sdata,2):-1:1
        tmp(n) = data-sdata(j,n);
    end
    win(j) = min(sum(tmp.^2));
    
%     win(j)=min(sqrt(sum(bsxfun(@minus,data,sdata(j,:)).^2,2)));
end

sqrt(max(win))

hth kinor