I have the following code
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
The combinations are supposed to be valid if the sum of A and some values of B are less than 3000.
Problem with my code is, the last value of B, B(3,3)
, is only accounted for once in the code.
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.
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)))