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

조회 수: 3 (최근 30일)
C Zeng
C Zeng 2012년 5월 22일
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!

채택된 답변

Sean de Wolski
Sean de Wolski 2012년 5월 22일
[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
C Zeng
C Zeng 2012년 5월 24일
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.
Sean de Wolski
Sean de Wolski 2012년 5월 25일
This is true. I messed up on thinking reshape() would account for the order of the cells being stacked. It did not, see update.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Daniel Shub
Daniel Shub 2012년 5월 24일
x = fullfact([3,3,3])-1
  댓글 수: 2
Oleg Komarov
Oleg Komarov 2012년 5월 24일
Thanks again!
C Zeng
C Zeng 2012년 5월 25일
Thank you, Daniel, it works here!

댓글을 달려면 로그인하십시오.

카테고리

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