Code covered by the BSD License  

Highlights from
nested 'for' to 'while'

image thumbnail
from nested 'for' to 'while' by Ligong Han
convert nested 'for' loop to 'while' loop

forfolding(expr,inflimit,suplimit,step,flen,clen,dlen)
function forfolding(expr,inflimit,suplimit,step,flen,clen,dlen)
if nargin < 3
    fprintf('Not enough input arguments.\n')
    return
end
n = length(inflimit);
if nargin < 7
    dlen = ones(1,n);
if nargin < 6
    clen = inf;
if nargin < 5
    flen = -inf;
if nargin < 4
    step = ones(1,n);
end
end
end
end
% flen is the floor of the total sum
% clen is the ceiling of the total sum
work     = [inflimit(1:end-1),0];
inflen   = inflimit.*dlen;
osum     = cumsum(inflen); %original cumsum
rsum     = cumsum(inflen(end:-1:1));rsum = rsum(end:-1:1); %reverse cumsum
csum     = osum+rsum-2*inflen; %csum(k) = cumsum(k-1)+rsum(k+1)
finish   = min(floor((clen-csum)./dlen),suplimit);
n        = length(inflimit);
p        = n; %p is a pointer
cnt = 0;
while p
    work(p) = work(p)+step(p);
    work(p+1:end) = inflimit(p+1:end);
    csum(p+1:end) = csum(p)+work(p)*dlen(p)-inflen(p+1:end);
    finish(p+1:end) = min(floor((clen-csum(p+1:end))./dlen(p+1:end)),...
        suplimit(p+1:end));
    start = ceil((flen-csum(n))/dlen(n));
    work(n) = max(start,work(n));
    if all(work <= suplimit & work >= inflimit) %work(n) <= suplimit(n) && work(n) >= inflimit(n)
        %-------------------------%
        %TODO: add your code here
        eval(expr);
         %for example:
         %disp(work);
         %fprintf('sum: %d\n\r',sum(work.*dlen));
        
        %-------------------------%
        cnt = cnt+1;
    end
    p = n;
    while p > 0 && work(p) >= finish(p)
        p = p-1;
    end
end
fprintf('total number of methods: %d\n',cnt);

Contact us