Generating vectors in MATLAB

I am wondering if there is an efficient way in MATLAB to generate all vectors of a fixed length with elements from a finite set.

For example, how can I build all vectors of length 5 with only 0 or 1 as elements?

+5
source share
4 answers

not quite what you need, but permv generates vector permutations. If you do not find the exact solution, you can adapt the vector permutations.

permv

+3
source

The correct way to build all vectors of length 5 using only 0 or 1 as elements

a = dec2bin(0:31,5) - '0';

I hope you understand why.

+10
source

MathWorks FileExchange - :

, , , :

VChooseKRO([0 1], 5)

:

C = {'a' 'b' 'c' 'd'};
C( VChooseKRO(1:numel(C), 2) )
+3

:

DEC2BIN AB ( woodchips), BITGET, . REPMAT, ( 32 5):

allCombos = bitget(repmat((0:31)',1,5),repmat(5:-1:1,32,1));

BITGET , :

vec = (0:31)';
allCombos = [bitget(vec,5) bitget(vec,4) bitget(vec,3) ...
             bitget(vec,2) bitget(vec,1)];

:

     Method      |  Average Time
-----------------+------------------
  DEC2BIN        |   0.000788 s
  BITGET+REPMAT  |   0.000727 s
  BITGET x5      |   0.000045 s

, BITGET .


: ( )

If you want to build a matrix of all possible vectors of zeros and ones having a length of 5, this would be one way to do this using the PERMS and UNIQUE functions (since PERMS creates duplicate rows):

allCombos = [0 0 0 0 0;
             unique(perms([0 0 0 0 1]),'rows'); ...
             unique(perms([0 0 0 1 1]),'rows'); ...
             unique(perms([0 0 1 1 1]),'rows'); ...
             unique(perms([0 1 1 1 1]),'rows'); ...
             1 1 1 1 1];
+1
source

All Articles