Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Find function
Date: Sun, 23 Nov 2008 00:50:17 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 27
Message-ID: <gga9c9$l1c$1@fred.mathworks.com>
References: <gg8c2k$s8d$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 1227401417 21548 172.30.248.35 (23 Nov 2008 00:50:17 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 23 Nov 2008 00:50:17 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:502564


"Gordon " <mloomis@gmail.com> wrote in message <gg8c2k$s8d$1@fred.mathworks.com>...
> I&#8217;m attempting to run a find command on two vectors A and B, I want to find the number of occurrences in vector a  that are <= every occurrence in vector b.  I can do this easily with a for loop, but it takes forever to run on large vectors.  Here is my code&#8230;
> 
> y=zeros(length(a),1);
> for i = 1:length(a)
>    a1 = a(i);
>    y(i) = length(find(b <= a1));
> end
> 
> a= [1;1;2;3;4;5;7;9;3]
> b=[ 1;2;3;4;1;2;3;3;3;4;1;1;2;3;4]
> y= [4;4;7;12;15;15;15;15;12]
> 
> This works fine with small vectors, but I want to do this with very large vectors.  Is there any way to do this in Matlab without using the For Loop?
> 
> Any help would be appreciated.

  I realized belatedly that the code I sent you has its inequality testing backwards with respect to the for-loop code you gave.  Here is the corrected version.  It now assumes that a and b are column vectors.  For large arrays it should be considerably faster than your for-loop method.

 [p,p] = sort([b;a]);
 t = cumsum(p<=length(b));
 q = (1:length(p)); q(p) = q;
 y = t(q(length(b)+1:end));

Roger Stafford