从现有矩阵中提取矩阵 [英] Extract matrix from existing matrix
问题描述
我已经编写了一个代码来生成一个四列矩阵,以获取总和等于9且每个数字从0到9的数字的所有组合.
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
两个零例
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 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
有人建议按上述顺序获取矩阵m
吗?
Any suggestions to get the matrix m
in the above order?
推荐答案
这是我目前能做的最好的事情,而我还没有在您的整个输入矩阵上对其进行过测试
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, :)
应返回m
包含N
0的行.
编辑:更新后,以下是完整代码的建议:
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
这篇关于从现有矩阵中提取矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!