Back to Code

rec_loop

A recursive loop function. Returns all permutations of vectors of length loop_depth containing numbers from 1 to N. E.g., loop_depth = 1 and N = 3 gives [1; 2; 3]; loop_depth = 3, N = 2 gives

     1     1     1
     1     1     2
     1     2     1
     1     2     2
     2     1     1
     2     1     2
     2     2     1
     2     2     2 

The function is useful when you need to nest loops, but don't know how deep the nesting will be.

function loop_matrix = rec_loop(varargin)

% loop_matrix = rec_loop(loop_depth, N)
%
% Thomas Gladwin, 2007.

loop_depth = varargin{1};
if length(varargin) > 2,
    current_level = varargin{2};
    N = varargin{3};
else,
    current_level = 1;
    N = varargin{2};
end;
if current_level == loop_depth,
    loop_matrix = (1:N)';
else,
    loop_matrix = [];
    to_the_right = rec_loop(loop_depth, current_level + 1, N);
    for n = 1:N,
        [nR, nC] = size(to_the_right);
        loop_matrix = [loop_matrix; ones(nR, 1) * n to_the_right];
    end;
end;