[英]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,則認為該組合有效。
我的代碼有問題, B(3,3)
的最后一個值B(3,3)
在代碼中只占一次。
如果運行代碼,則會在第12行注意到V
一個單元格包含[0;0;0;800]
,但是還有其他可能的組合,例如[1;0;0;800]
。 當SA + (1 + 800) < 3000
,代碼不會顯示這種可能性。
我不知道為什么,有人可以幫我調試一下,找出為什么跳過某些組合嗎? 特別是B(3,3)
?
我懷疑這條線沒有完全按照您的意圖執行:
if ~isequal(rows, unique(rows))
相反,請嘗試以下操作:
if ~isequal(length(rows), length(unique(rows)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.