use "for loop" for n times but n is not fixed

2 次查看(过去 30 天)
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

回答(3 个)

Jan
Jan 2013-1-4
编辑:Jan 2013-1-4
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.

Daniel Shub
Daniel Shub 2013-1-4
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

Andrei Bobrov
Andrei Bobrov 2013-1-4
v = 1:5;
n = 3;
a = cell(1,n);
[a{:}] = ndgrid(v);
out = cell2mat(cellfun(@(x)x(:),a,'un',0));

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by