I need to create all a list of all possible states

2 次查看(过去 30 天)
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]

采纳的回答

Kevin
Kevin 2016-4-27
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
  4 个评论
V A
V A 2016-4-27
This way works only for N<=30.
Error using repmat
Requested 2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2 (16.0GB) array exceeds
maximum array size preference. Creation of arrays greater than this limit may take a long time and
cause MATLAB to become unresponsive. See array size limit or preference panel for more information.
This error is super strange, because it doesn't take 16GB to create array I need....
Kevin
Kevin 2016-4-27
But if N = 30, then
>> 2^30
ans =
1.0737e+09
So the matrix (that contains all possible combinations) will have 1 billion rows and 30 columns. Each matrix element takes 8 bytes. So total number of bytes ~= 240 GB.
Right?

请先登录,再进行评论。

更多回答(1 个)

Roger Stafford
Roger Stafford 2016-4-27
A = zeros(2^N,N);
for k = 0:2^N-1
A(k+1,:) = 2*(dec2bin(k,N)-'0')-1;
end
  2 个评论
V A
V A 2016-4-27
This solution doesn't work for me for N>=26.
Error using zeros
Requested 67108864x26 (13.0GB) array exceeds maximum array size preference. Creation of arrays
greater than this limit may take a long time and cause MATLAB to become unresponsive. See array size
limit or preference panel for more information.
Subscripted assignment dimension mismatch.
Roger Stafford
Roger Stafford 2016-4-28
If that is the limit on your array sizes, then no 'double' solution for N>=26 could work. The matrix you request as an output is that size. You could probably get up to N = 29 by using the 'uint8' format, but that would be as far as you could go.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Operators and Elementary Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by