Asked by lg
on 4 Jan 2013

hi

i have a problrm with "for loop"

consider that i only have 5 integers, say 1 2 3 4 5

if the input n=1

i will expect i will get a set of data [1] [2] [3] [4] [5]

if n=2

i will get

[1 1] [1 2] [1 3] [1 4] [1 5]

[2 1] [2 2] [2 3] [2 4] [2 5]

[3 1] [3 2] [3 3] [3 4] [3 5]

[4 1] [4 2] [4 3] [4 4] [4 5]

[5 1] [5 2] [5 3] [5 4] [5 5]

actually, i want to get all the permutations of a n-digit number which can take the value of 1 2 3 4 5 (in this case)

of course if i know the number of digits (say n=2), i can write a for loop like this

for i = 1:5

for j = 1:5

A = [i,j]

end

end

however, i would like to input n for any integers and then matlab will generate all the possible cases autometically

for example, if i input n = 2, i will get 25 results listed above

if i input n = 3, i will get 125 results...

thanks for the help

*No products are associated with this question.*

Answer by Jan Simon
on 4 Jan 2013

Edited by Jan Simon
on 4 Jan 2013

If you want to do this fast: FEX: VChooseKRO.

If you want to find out, how to solve such question in general:

n = 5; k = 3; m = zeros(n^k, k); v = ones(1, 3); c = 0; ready = false; while ~ready % Store current value in the output matrix: c = c + 1; m(c, :) = v;

% Increase the current value, care for overflow: q = k; while ~ready v(q) = v(q) + 1; if v(q) <= n break; % Index inside limit, proceed with outer loop end v(q) = 1; % Reset current index to 1 q = q - 1; % Go to previous index if q == 0 % All indices are exhausted ready = true; % Stop both loops end end end

By this way, you do not increase a scalar in a FOR loop, but the elements of a vector in a WHILE loop.

There are more efficient methods to create permutations. Exploiting the obvious structure of the output would be more efficient.

Answer by Daniel
on 4 Jan 2013

I wouldn't do it this way, but recursion is a useful technique when you have an unknown number of loops.

function x = looper(n) if n > 1 temp = looper(n-1); x = []; for ii = 1:5 x = [x; repmat(ii, length(temp), 1), temp]; end else x = (1:5)'; end end

Answer by Andrei Bobrov
on 4 Jan 2013

v = 1:5; n = 3;

a = cell(1,n); [a{:}] = ndgrid(v); out = cell2mat(cellfun(@(x)x(:),a,'un',0));

Opportunities for recent engineering grads.

## 0 Comments