MATLAB: I need to create all a list of all possible states

all subsetslistvector

I have discrete variables a_i=[1 -1]. I need to create a list of all states in system of N variables(# of states = 2^N). Or in other words I have a vector of length N, each component can have two values. How can I generate a list of all possible vectors?
For instance, for 3 variables I need to have
[1 1 1]
[1 1 -1]
[1 -1 1]
[-1 1 1]
[1 -1 -1]
[-1 1 -1]
[-1 -1 1]
[-1 -1 -1]

Best Answer

I have written my own function to do what you are asking for. The trick is to use the MATLAB function ndgrid.
>> A = allcombs({[1 -1], [1 -1], [1 -1]})
A =
1 1 1
1 1 -1
1 -1 1
1 -1 -1
-1 1 1
-1 1 -1
-1 -1 1
-1 -1 -1
Here is the definition of my function allcombs.m:
function A = allcombs(experimentOutcomes)
experimentOutcomes = flipud(experimentOutcomes(:));
c = cell(1, numel(experimentOutcomes));
[c{:}] = ndgrid(experimentOutcomes{:});
c = fliplr(c);
A = cell2mat(cellfun(@(v)v(:), c, 'UniformOutput',false));
end