Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: vertorize a loop
Date: Fri, 3 Jun 2011 05:21:04 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 26
Message-ID: <is9r00$7o7$1@newscl01ah.mathworks.com>
References: <is8sko$moh$1@newscl01ah.mathworks.com> <is8t9c$oml$1@newscl01ah.mathworks.com> <is8ud0$ruu$1@newscl01ah.mathworks.com> <is97qs$lt9$1@newscl01ah.mathworks.com> <is99dg$pmr$1@newscl01ah.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-04-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: newscl01ah.mathworks.com 1307078464 7943 172.30.248.35 (3 Jun 2011 05:21:04 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 3 Jun 2011 05:21:04 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:729991

"Gareth Lennox" <celtlen@yahoo.co.uk> wrote in message <is99dg$pmr$1@newscl01ah.mathworks.com>...
> newpossible = [];
> for i = 1:size(possible,1)
>     for j = possible(i,iter-1)+1:nsites
> newpossible(end+1,1:iter) = [possible(i,1:iter-1) j];
> end
> end
> And it is this loop that i'd like to vectorize. 
- - - - - - - - - -
  Your for-loop code wouldn't work for me unless 'iter' is equal to one greater than the number of columns in 'possible', which is the case in all the examples you have shown, so I have written it to be just that:

 iter = size(possible,2)+1;
 v = nsites-possible(:,iter-1);
 s = cumsum([1;v]);
 sz = s(end)-1;
 s = s(1:end-1);
 t = accumarray(s,-v,[sz,1]) + 1;
 t(1) = t(1) + nsites;
 newpossible = zeros(sz,iter);
 newpossible(:,iter) = cumsum(t);
 t = accumarray(s,1,[sz,1]);
 newpossible(:,1:iter-1) = possible(cumsum(t),:);

  This vectorized version looks more complicated than your for-loop solution.  I had trouble working it out and there may be easier methods.  It is possible that if you allocate space for 'newpossible' in advance using only the 'sz' computation above, your for-loop solution might then be faster than this code.  Adding elements to 'newpossible' one at a time starting with an empty array as you do can slow down computation in a dramatic way for large arrays.

Roger Stafford