5
votes

I have written a code to generate a matrix with four columns to get all combinations of numbers whose sum is equal to 9 and each number varies from 0 to 9.

m = zeros(220, 4);
pd = 9;
i = 1;
for p = 0:1:pd
    for q = 0:1:pd-p
        for a = 0:1:pd-q-p
            m(i,:) = [p, q, a, pd-a-q-p];
            i = i+1;
        end
    end
end
m

Now i want filter the arrays with no zero, one zero, two zeros, three zeros. Like, Three zero case

0 0 0 9

Two zero case

0 0 1 8
0 0 2 7
.
.
0 0 8 1

One zero case

0 1 1 7
0 1 2 6
.
.
.
0 7 1 1

and no zero case

1 1 1 6
1 1 2 5
.
.
6 1 1 1

and so on..

Any suggestions to do that or any alternative method ?
Update:

0 0 0 9
0 0 1 8
0 0 2 7
    .
    .
0 0 8 1
0 1 1 7
0 1 2 6
    .
    .
    .
0 7 1 1
1 1 1 6
1 1 2 5
    .
    .
6 1 1 1

Any suggestions to get the matrix m in the above order?

4
I may overlook something - but aren't you producing the matrix in this specific order?bdecaf

4 Answers

7
votes

This is the best I can do right now, and I haven't tested it on your entire input matrix

m(sum(m == 0, 2) == N, :)

should return the rows of m which contain N 0s.

EDIT: following your update, here's a suggestion for the complete code:

A = zeros(size(m));
k = 1;
for N = (size(m, 2) - 1):-1:0
    rows = (sum(m == 0, 2) == N);
    idx = k:k + sum(rows) - 1;
    A(idx, :) = m(rows, :);
    k = idx(end) + 1;
end
5
votes

To sort by the number of leading zeros in a row, all you need is sortrows(m).

To sort by the total number of zeros in a row, use High Performance Mark's answer.

3
votes

You can use the following function to get all rows of matrix A that have n zeros:

function rows = nzrows(A, n)
  s = sum(A == 0, 2);
  rows = A(s == n, :);
end
2
votes

This is what I came up with:

zero_index =[];
one_index =[];
two_index =[];
three_index =[];

for i=1:size(m,1)
    if(sum(m(i,:)==0)==0)
        zero_index = [zero_index    i];
    end
    if(sum(m(i,:)==0)==1)
        one_index = [one_index  i];
    end
    if(sum(m(i,:)==0)==2)
        two_index=  [two_index i];
    end

    if(sum(m(i,:)==0)==3)
        three_index =   [three_index i];
    end

end

m(zero_index,:)
m(one_index,:)
m(two_index,:)
m(three_index,:)

Hope it helps.