Matrix with all possible value combinations
1 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
I have a quick question. Lets say i want to form a matrix with all possible combinations of some acceptable value, eg. lets say i have 3 elements and i the possible values are 0 1 2 so the matrix would be
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
and so on for all the possible 3^3 combinations. How can i do this with Matlab for cases that could span between many other possible values (0 1 2 3 4 5 6 7 8...) and for many more columns this time (not only 3).
Thanks.
0 个评论
采纳的回答
the cyclist
2014-4-13
There is a slick way to do this when your vector is the N elements [0 1 2 ... N-1]:
N = 3;
m = dec2base(0:N^N-1, N)-'0';
Notice that dec2base gives a string result, and "subtracting" '0' from that string gives the numeric result you want.
For N=8, this takes about 5 seconds to run on my machine. (I think larger N than that is impractical from a memory point of view.)
If your vector is not so super-specialized, but the elements are unique, then I think this method would still be useful. You could generate the above first, then do a substitution to get to the elements you actually want.
2 个评论
the cyclist
2014-4-13
There's almost certainly a better solution than this, but in case nothing else surfaces:
NCOL = 8; % Can't be more than 8, by memory constraint
MAXVAL = 2;
m = dec2base(0:NCOL^NCOL-1, NCOL)-'0';
% Excise values that are bigger than the one you want.
m(any(m>MAXVAL,MAXVAL),:) = [];
m(:,any(m>MAXVAL,1)) = [];
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!