【问题标题】:Need help debugging this code in Matlab需要帮助在 Matlab 中调试此代码
【发布时间】:2013-02-23 14:44:18
【问题描述】:

我有以下代码

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) 在代码中只占了一次。

如果您运行代码,您会注意到V 的一个单元格在第12 行包含[0;0;0;800]。但还有其他可能的组合,例如[1;0;0;800]。其中SA + (1 + 800) &lt; 3000,但是代码没有打印出这种可能性。

我不知道为什么,有人可以帮我调试一下并找出为什么会跳过某些组合吗?特别是B(3,3)?

【问题讨论】:

    标签: arrays debugging matlab cell combinations


    【解决方案1】:

    我怀疑这条线并没有完全按照您的意愿行事:

    if ~isequal(rows, unique(rows))
    

    试试这个:

    if ~isequal(length(rows), length(unique(rows)))
    

    【讨论】:

    • 哦,完美.. 早上 7 点,我从下午 6 点开始一直在编写代码.. 难怪我错过了!哈哈好眼力,非常感谢。现在我可以睡一觉了。
    • 你能快速告诉我为什么顺便解决了这个问题吗?
    • 试试这个:a = [1 1 3 5] 然后是 unique(a)。你会得到 ans = [1 3 5]。因此,基本上 unique() 仅以排序方式返回唯一元素。因此,当您传递 [2 0] 之类的组合时,unique() 将返回 [0 2],if 语句将为 true(falsely :P)
    猜你喜欢
    • 2013-08-12
    • 2010-11-04
    • 2013-03-24
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多