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$>
References: <is8sko$moh$> <is8t9c$oml$> <is8ud0$ruu$> <is97qs$lt9$> <is99dg$pmr$>
Reply-To: <HIDDEN>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: 1307078464 7943 (3 Jun 2011 05:21:04 GMT)
NNTP-Posting-Date: Fri, 3 Jun 2011 05:21:04 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: comp.soft-sys.matlab:729991

"Gareth Lennox" <> wrote in message <is99dg$pmr$>...
> 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