help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Vectorization quiz


From: Miroslaw Kwasniak
Subject: Re: Vectorization quiz
Date: Tue, 03 May 2011 21:23:44 +0200
User-agent: Mutt/1.5.19 (2009-01-05)

On Thu, Apr 21, 2011 at 10:49:03AM +0200, Daniel Arteaga wrote:
> Hi,
>
> How could I vectorize the following piece of code?
>
> P = zeros(size(fInf));
> for i = 1:length(fInf)
>       P(i) = sum( S2( fLin > fInf(i) & fLin < fSup(i) ) );
> endfor

Fast (but O(n*log(n)) ;), not fully tested with possible drawbacks:
- precision lost
- cumsum is limited by double type range

% sample data

 clear;
 fInf=(-10:2:10).';
 fSup=fInf+5;
 S2=(20:-1:-20).';
 fLin=-S2;

% new algorithm
 
 l     = length(fInf);
 [i,i] = sort(   [ fSup;       fLin; fInf       ]);
 P     = cumsum( [ zeros(l,1); S2;   zeros(l,1) ](i));
 [i,i] = sort(i);
 P     = P(i(1:l)) - P(i(end+1-(l:-1:1)));
 clear i l

% old algorithm

  P_old = zeros(size(fInf));
  for i = 1:length(fInf);
     P_old(i) = sum( S2( fLin > fInf(i) & fLin < fSup(i) ) );
  endfor;

%test

  all(P==P_old)


reply via email to

[Prev in Thread] Current Thread [Next in Thread]