需要帮助在Matlab中调试此代码 [英] Need help debugging this code in Matlab
问题描述
我有以下代码
B=[1 2 3; 10 20 30 ; 100 200 300 ; 500 600 800];
A=[100; 500; 300 ; 425];
SA = sum(A);
V={}; % number of rows for cell V = num of combinations -- column = 1
n = 1;
arr = zeros(1,length(B))
for k = 1:length(B)
for idx = nchoosek(1:numel(B), k)'
rows = mod(idx, length(B))
if ~isequal(rows, unique(rows)) %if rows not equal to unique(rows)
continue %combination possibility valid
end %Ignore the combination if there are two elements from the same row
B_subset = B(idx)
if (SA + sum(B_subset) <= 3000) %if sum of A + (combination) < 3000
rows( rows==0 )=4
arr(rows) = B_subset(:)
V(n,1) = {arr}
n = n + 1
arr = zeros(1,length(B))
end
end
end
如果A和B的某些值之和小于3000,则该组合才有效.
The combinations are supposed to be valid if the sum of A and some values of B are less than 3000.
我的代码存在问题,B的最后一个值B(3,3)
在代码中仅占一次.
Problem with my code is, the last value of B, B(3,3)
, is only accounted for once in the code.
如果运行代码,则会在第12行注意到包含[0;0;0;800]
的V
单元格之一.但是还有其他可能的组合,例如[1;0;0;800]
.在SA + (1 + 800) < 3000
位置,但是代码没有显示这种可能性.
If you run the code, you will notice one cell of V
containing [0;0;0;800]
at row 12. But there are other combinations possible as well such as [1;0;0;800]
. Where SA + (1 + 800) < 3000
, however the code does not print this possibility.
我不知道为什么,有人可以帮我调试一下,找出为什么跳过某些组合吗?特别是B(3,3)
吗?
I cannot figure out why, can someone please help me debug this and find out why some combinations are skipped ? especially B(3,3)
?
推荐答案
我怀疑这行代码未完全符合您的预期:
I suspect that this line is not doing exactly what you intended:
if ~isequal(rows, unique(rows))
相反,请尝试以下操作:
Instead, try this:
if ~isequal(length(rows), length(unique(rows)))
这篇关于需要帮助在Matlab中调试此代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!