Path: news.mathworks.com!newsfeed-00.mathworks.com!newsfeed2.dallas1.level3.net!news.level3.com!postnews.google.com!z8g2000prd.googlegroups.com!not-for-mail
From: Bob Alvarez <ralvarez@spambob.net>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Help in vectorizing code
Date: Wed, 29 Apr 2009 11:43:04 -0700 (PDT)
Organization: http://groups.google.com
Lines: 60
Message-ID: <3eddb5a1-cef2-41de-996f-cdaa08c694df@z8g2000prd.googlegroups.com>
References: <1e6f5074-edce-417a-b0a5-b62db0fb033f@w31g2000prd.googlegroups.com> 
	<gt8r5g$am8$1@fred.mathworks.com>
NNTP-Posting-Host: 216.103.212.87
Mime-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
X-Trace: posting.google.com 1241043616 1541 127.0.0.1 (29 Apr 2009 22:20:16 GMT)
X-Complaints-To: groups-abuse@google.com
NNTP-Posting-Date: Wed, 29 Apr 2009 22:20:16 +0000 (UTC)
Complaints-To: groups-abuse@google.com
Injection-Info: z8g2000prd.googlegroups.com; posting-host=216.103.212.87; 
	posting-account=pNrldAoAAAB5GlVBDJqvQa-_ca5yFHCO
User-Agent: G2/1.0
X-HTTP-UserAgent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) 
	Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729),gzip(gfe),gzip(gfe)
Xref: news.mathworks.com comp.soft-sys.matlab:536280


On Apr 28, 11:13 pm, "Jos " <#10...@fileexchange.com> wrote:
> Bob <ralva...@spambob.net> wrote in message <1e6f5074-edce-417a-b0a5-b62d=
b0fb0...@w31g2000prd.googlegroups.com>...
> > For a Monte Carlo simulator of compound Poisson noise, I need to add a
> > variable number of columns of each row of a matrix. So far, I have not
> > been able to vectorize the for loop and any help will be appreciated.
>
> > Here is an example:
> > >> d = magic(5)
>
> > d =
>
> >     17    24     1     8    15
> >     23     5     7    14    16
> >      4     6    13    20    22
> >     10    12    19    21     3
> >     11    18    25     2     9
>
> > >> idxs = round(linspace(1,3,5))
>
> > idxs =
>
> >      1     2     2     3     3
>
> >  for k=1:5
> >     totals(k) = sum(d(k,1:idxs(k)),2);
> >  end
>
> > >> totals'
>
> > ans =
>
> >     17    28    10    41    54
>
> > TIA
>
> What about simple indexing after applying cumsum:
>
> % data
> d = magic(5)
> idxs = round(linspace(1,3,5))
>
> % engine
> d2 = cumsum(d,2) ;
> totals = d2(sub2ind(size(d2),1:numel(idxs),idxs))
>
> hth
> Jos

Good idea. Timed the following code:
%% code from Jos
tic
d = cumsum(randn(m,ceil(max(R))),2);
s = d(sub2ind(size(d),1:numel(R),R));
toc
 result:
Elapsed time is 0.027088 seconds. % Jos
Elapsed time is 0.019429 seconds. % for loop
The for loop seems to win because it does not have to compute a full
matrix, just the specified length random variable at each trial.