Matrix with all possible value combinations

3 views (last 30 days)
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.

Accepted Answer

the cyclist
the cyclist on 13 Apr 2014
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 Comments
Raldi
Raldi on 13 Apr 2014
Not exactly what I want,
what if I had 4 samples (columns) and 3 possible values (eg 0 1 2)?
the cyclist
the cyclist on 13 Apr 2014
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)) = [];

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!