Path: news.mathworks.com!not-for-mail
From: "John D'Errico" <woodchips@rochester.rr.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: How to find a list of floats in another list of floats
Date: Sun, 10 Feb 2008 22:17:01 +0000 (UTC)
Organization: John D'Errico (1-3LEW5R)
Lines: 51
Message-ID: <font4t$ifr$1@fred.mathworks.com>
References: <47af565c$0$1103$4c368faf@roadrunner.com> <fonsi6$bp4$1@fred.mathworks.com>
Reply-To: "John D'Errico" <woodchips@rochester.rr.com>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1202681821 18939 172.30.248.37 (10 Feb 2008 22:17:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 10 Feb 2008 22:17:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 869215
Xref: news.mathworks.com comp.soft-sys.matlab:450479


"Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid> wrote in 
message <fonsi6$bp4$1@fred.mathworks.com>...
> "Peter de B. Harrington" <peter.harrington@ohio.edu> wrote in message 
> <47af565c$0$1103$4c368faf@roadrunner.com>...
> > Hi:
> > 
> > I was wondering if there are any clever tricks to search for sets of real 
> > numbers in a larger list, especially without using a for loop.  I only know 
> > how to do the search for one element at a time.
> > 
> > A = [1.0, 2.0];
> > B = [1.0, 2.0, 3.0];
> > 
> > for i = 1:length(A)
> >   [t, ind(i)] = min(abs(A(i)-B));
> > end
> > 
> > Just curious if there is a better way to write this code.
> > 
> > Thanks in advance,
> > 
> > Pete 
> ---------
>   Here is how I would have performed just the operation you described in 
your 
> for-loop construct using my antiquated version of matlab.  I'm not at all 
sure 
> that it would be faster on a newer version, however.
> 
>  [a,b] = meshgrid(A,B);
>  [ignore,ind] = min(abs(a-b),[],1);
> 
> Roger Stafford

As it turns out, using bsxfun can help quite
a bit here.

n = 1000;
A = rand(n,1);B = rand(n,1);

tic,[x,y] = meshgrid(A,B);d=abs(x-y);toc
Elapsed time is 0.221196 seconds.

d = abs(bsxfun(@minus,A,B'));toc
Elapsed time is 0.072752 seconds.

Unfortunately, bsxfun appeared only in the
last release or so. It never has to create
those intermediate arrays.

John