Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Help in vectorizing code
Date: Wed, 29 Apr 2009 06:13:04 +0000 (UTC)
Organization: Erasmus MC
Lines: 46
Message-ID: <gt8r5g$am8$1@fred.mathworks.com>
References: <1e6f5074-edce-417a-b0a5-b62db0fb033f@w31g2000prd.googlegroups.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 1240985584 10952 172.30.248.35 (29 Apr 2009 06:13:04 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 29 Apr 2009 06:13:04 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 870065
Xref: news.mathworks.com comp.soft-sys.matlab:536091


Bob <ralvarez@spambob.net> wrote in message <1e6f5074-edce-417a-b0a5-b62db0fb033f@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