how to write code to try every combination of N-dim vector?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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!
0 Kommentare
Akzeptierte Antwort
Sean de Wolski
am 22 Mai 2012
[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 Kommentare
Sean de Wolski
am 25 Mai 2012
This is true. I messed up on thinking reshape() would account for the order of the cells being stacked. It did not, see update.
Weitere Antworten (1)
Siehe auch
Kategorien
Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!