How to generate a matrix of vector combinations with zeros for excluded elements?

I want to create a matrix from all combinations of elements of one vector that satisfy the condition

For example, I have this vector

a = [1 2 3 4 5]

and want to create a matrix like

a = [1 0 0 0 0;
     1 2 0 0 0;
     1 2 3 0 0;
     1 2 3 4 0;
     1 2 3 4 5;
     0 2 0 0 0;
     0 2 3 0 0;
     ........;]

and then get the lines that satisfy the condition, I can use the command:

b = sum(a')' > value

but i don't know how to generate a matrix

+4
source share
1 answer

You can create all possible binary combinations to determine the desired matrix:

a = [1 2 3];
n = size(a,2);

% generate bit combinations
c =(dec2bin(0:(2^n)-1)=='1');
% remove first line
c = c(2:end,:)
n_c = size(c,1);

a_rep = repmat(a,n_c,1);
result = c .* a_rep

Conclusion:

c =

 0     0     1
 0     1     0
 0     1     1
 1     0     0
 1     0     1
 1     1     0
 1     1     1


result =

 0     0     3
 0     2     0
 0     2     3
 1     0     0
 1     0     3
 1     2     0
 1     2     3
+2
source

All Articles