0
调试这个代码,我有以下代码需要帮助在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的最后一个值,B(3,3)
,在代码中只占一次。
如果您运行代码,您会注意到第12行包含[0;0;0;800]
的一个单元格V
。但还有其他可能的组合,例如[1;0;0;800]
。凡SA + (1 + 800) < 3000
,但代码不打印这种可能性。
我不明白为什么,有人可以帮我调试,并找出为什么一些组合被跳过?特别是B(3,3)
?
哦完美..其早上7点,我一直在工作的代码因为6pm ..所以难怪我错过了!哈哈好眼睛,非常感谢你。现在我可以睡一觉了。 – NLed 2013-03-08 07:02:27
你能快点告诉我为什么这个问题能解决这个问题吗? – NLed 2013-03-08 07:03:26
试试这个:a = [1 1 3 5]然后唯一(a)。你会得到ans = [1 3 5]。所以,基本上unique()只是以一种排序的方式返回唯一的元素。所以,当你传递像[2 0]这样的组合时,unique()返回[0 2] if语句将为true(falsely:P) – Kishore 2013-03-08 07:09:20