Matrix with all possible value combinations

조회 수: 4 (최근 30일)
Raldi
Raldi 2014년 4월 13일
댓글: the cyclist 2014년 4월 13일
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.

채택된 답변

the cyclist
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
Raldi
Raldi 2014년 4월 13일
Not exactly what I want,
what if I had 4 samples (columns) and 3 possible values (eg 0 1 2)?
the cyclist
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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by