MATLAB Answers

C Zeng

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

Asked by C Zeng
on 22 May 2012

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!



No products are associated with this question.

2 Answers

Answer by Sean de Wolski
on 22 May 2012
 Accepted answer

[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}(:);


C Zeng
on 22 May 2012

Can I write like this:
For i=1 to 3^N
then define function and solve the value;
compare and find the maximizer;

It works well I think.

C Zeng
on 24 May 2012

Hi, the code does not work and try all combinations:
n = 4
[C{1:n}] = ndgrid(0:2);

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.

Answer by Daniel Shub
on 24 May 2012

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


Thanks again!

C Zeng
on 25 May 2012

Thank you, Daniel, it works here!

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!