how to write code to try every combination of N-dim vector?

Hello, I want to write a code to try every combination of a N-dimentional vector(with entry 0 or 1 or 2). For example, if N=3, all combinations are (0,0,0)(0,0,1)...(2,2,2) and there are 3^N=27.
One brutal way is for commands: for i=0:2->for j=... but I have to write N these for commands, which is not wise. I wonder it there a fast and smart way to try all combinations?
Thanks a lot!

 Respuesta aceptada

[xx yy zz] = ndgrid(0:2);
[xx(:) yy(:) zz(:)]
Generalized (fixed)
n = 4
[C{1:n}] = ndgrid(0:2);
for ii = n:-1:1
M(:,ii) = C{ii}(:);
end

9 comentarios

C Zeng
C Zeng el 22 de Mayo de 2012
Hello, Sean, thanks, but N is also a parameter her, and I do not know if there is 3. In fact, there might be N=5 or 20. If so, how to make it work?
Thank you!
see addendum
C Zeng
C Zeng el 22 de Mayo de 2012
Oh, great! Thank you so much!
If I want to try all combination and find the maximizer, how could I write the recurrent command? for example, I have a function of the 4-dim vector, and it is the sum of 4 entries, I want to compare and find the maximizer. Of course it would be (2,2,2,2) but I want computer to visit every combination and compare and then find the maximizer and maximum value which is 8. Could you advise?
You are awesome!
M = reshape(...from above)
sum(M,2);
[~, row_max] = max(sum(M,2))
C Zeng
C Zeng el 22 de Mayo de 2012
Hi, Sean, thanks!
Sorry I did not make it clear! :-) The function can be complex, and I want to visit every combination (say 3^N) and solve the function value and then compare, what is the general code for it please?
Hope you can understand!
C Zeng
C Zeng el 22 de Mayo de 2012
Can I write like this:
For i=1 to 3^N
[a1,a2,a3,a4]=M(i,:);
then define function and solve the value;
compare and find the maximizer;
end;
It works well I think.
C Zeng
C Zeng el 24 de Mayo de 2012
Hi, the code does not work and try all combinations:
n = 4
[C{1:n}] = ndgrid(0:2);
reshape(vertcat(C{:}),[],n)
In deed, it has many same combinations.
This is true. I messed up on thinking reshape() would account for the order of the cells being stacked. It did not, see update.

Iniciar sesión para comentar.

Más respuestas (1)

x = fullfact([3,3,3])-1

2 comentarios

Thanks again!
C Zeng
C Zeng el 25 de Mayo de 2012
Thank you, Daniel, it works here!

Iniciar sesión para comentar.

Categorías

Preguntada:

el 22 de Mayo de 2012

Community Treasure Hunt

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

Start Hunting!

Translated by