Path: news.mathworks.com!not-for-mail
From: "Bruno Luong" <b.luong@fogale.findmycountry>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Vectorizing data lookback?
Date: Wed, 3 Sep 2008 19:11:02 +0000 (UTC)
Organization: FOGALE nanotech
Lines: 36
Message-ID: <g9mng6$hbc$1@fred.mathworks.com>
References: <g9db32$oq6$1@fred.mathworks.com>
Reply-To: "Bruno Luong" <b.luong@fogale.findmycountry>
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 1220469062 17772 172.30.248.38 (3 Sep 2008 19:11:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 3 Sep 2008 19:11:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 390839
Xref: news.mathworks.com comp.soft-sys.matlab:488461




> 
> I've been trying to vectorize this function as well to
> improve the speed, but I can't wrap my brain around it. Any
> suggestions?

ndata=750e3;
nwin=25;
upper=10;

data=round(upper*rand(1,ndata));

% for loop
tic
output1=zeros(size(data));
for ii = nwin+1:length(data)
     if data(ii) > max( data(ii-nwin:ii-1) );
          output1(ii) = 1;
     else
          output1(ii) = 0;
     end
end
toc % Elapsed time is 9.436772 seconds.

% expanding vectorized
tic
[I J]=ndgrid(2:nwin+1,1:ndata);
temp = data(max(J-I+1,1));
temp(J<I)=Inf;
output2=all(bsxfun(@gt,data,temp),1);
toc % Elapsed time is 2.461195 seconds.

% check the results are identical
all(output1==output2)

% Bruno