MATLAB Answers

Raldi
2

Matrix with all possible value combinations

Asked by Raldi
on 13 Apr 2014
Latest activity Commented on by the cyclist
on 13 Apr 2014
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 Comments

Sign in to comment.

Products

1 Answer

Answer by the cyclist
on 13 Apr 2014
 Accepted Answer

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

Not exactly what I want,
what if I had 4 samples (columns) and 3 possible values (eg 0 1 2)?
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.