Gunther已经走上了正轨。你要选择一个元素,如果
- 非零的行cumsum为1 和
- 非零的列cumsum为1 和
- 元素本身是非零。
下面的代码解决了这个问题:然而
A = [0, 0, 3, 4;
4, 3, 2, 0;
2, 0, 2, 0];
batches = cell(0);
while any(A(:)~=0)
selector = cumsum(A~=0, 1) .* cumsum(A~=0, 2) .* (A~=0) == 1;
batches{end+1} = A .* selector;
A(selector) = 0;
end
注意,由于它的第二批是
0 0 0 4
0 3 0 0
2 0 0 0
这意味着返回的解决方案不是最佳的剩余矩阵元素是从同一列:
0 0 0 0
0 0 2 0
0 0 2 0
不幸的是,你不能在同一批次中绘制它们。所以你最终得到四批而不是三批。
编辑:也许,这是一个好主意,首先选择这些元素,这些元素出现在具有很多非零的行/列中。例如,可以使用这些权重
weight = repmat(sum(A~=0, 1), size(A, 1), 1) ...
.* repmat(sum(A~=0, 2), 1, size(A, 2)) .* (A~=0)
weight =
0 0 6 2
6 3 9 0
4 0 6 0
下面的算法
batches = cell(0);
while any(A(:)~=0)
batch = zeros(size(A));
weight = repmat(sum(A~=0, 1), size(A, 1), 1) ...
.* repmat(sum(A~=0, 2), 1, size(A, 2)) .* (A~=0);
while any(weight(:)~=0)
[r,c] = find(weight == max(weight(:)), 1);
batch(r,c) = A(r,c);
A(r,c) = 0;
weight(r,:) = 0;
weight(:,c) = 0;
end
batches{end+1} = batch;
end
返回这些批次。
batches{:}
ans =
0 0 0 4
0 0 2 0
2 0 0 0
ans =
0 0 3 0
4 0 0 0
0 0 0 0
ans =
0 0 0 0
0 3 0 0
0 0 2 0
所以它至少在这个小测试案例中起作用。
现在好了,那个循环看起来非常熟悉...... :) –
@Rody:是的。对你的算法结构和我的权重感谢;-) – Mehrwolf
顺便说一句,我认为总结repmats而不是乘以它们可能会更好。 – Mehrwolf