Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract matrix from existing matrix

Tags:

matrix

matlab

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?

like image 853
noufal Avatar asked Jan 17 '13 12:01

noufal


People also ask

How do you extract a matrix?

You can extract a submatrix by using subscripts to specify the rows and columns of a matrix. Use square brackets to specify subscripts. For example, if A is a SAS/IML matrix, the following are submatrices: The expression A[2,1] is a scalar that is formed from the second row and the first column of A.

How do I extract a matrix in MATLAB?

MATLAB extracts the matrix elements corresponding to the nonzero values of the logical array. The output is always in the form of a column vector. For example, A(A > 12) extracts all the elements of A that are greater than 12. Or you could replace all the spaces in a string matrix str with underscores.


Video Answer


1 Answers

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
like image 186
High Performance Mark Avatar answered Sep 26 '22 22:09

High Performance Mark