# find possible combinations of each row of matrix and allocate their respective values into 2 different matrices

1 view (last 30 days)
JL on 11 Sep 2019
Commented: JL on 14 Sep 2019
Hi everyone, I have 2 matrices, A and B. I would like to produce C and D by 1) listing down possible combinations within each row. If there is zero, just ignore it. For example, in row 1 of B, it will be just 2 3 while the row 2 will have combinations of 2 3, 2 4 and 3 4. then 2) I would like to put the values of A respectively to B's combinations
A = [0.3939
0.3116]
B = [2 3 0
2 3 4]
expected results
C = [0.3939 % from row 1 of A
0.3116 % from row 2 of A
0.3116 % from row 2 of A
0.3116 % from row 2 of A
];
D = [2 3 % from row 1 of B
2 3 % from row 2 of B
2 4 % from row 2 of B
3 5 % from row 2 of B
];
##### 2 CommentsShowHide 1 older comment
JL on 11 Sep 2019
there's no repeat of the same number

the cyclist on 11 Sep 2019
Edited: the cyclist on 12 Sep 2019
% The input data
A = [0.3939
0.3116];
B = [1 16 17 6 9 0 0 0 0 0 0 0 0 0
1 16 17 6 7 8 10 0 0 0 0 0 0 0
];
% Find the size of B, which is used a lot in the algorithm
[mb,nb] = size(B);
% Preallocate the output arrays, allowing for the most possible pairs
% within a row
maxPossiblePairs = nchoosek(nb,2);
C = zeros(mb*maxPossiblePairs,1);
D = zeros(mb*maxPossiblePairs,2);
% For each row of B, find the unique pairs of values. (Worry about zeros later.)
% Place those values into the correct segment of D.
% Put that row's value of A into the correct segment of C.
for ib = 1:mb
rowIndex = (ib-1)*maxPossiblePairs+1:ib*maxPossiblePairs;
D(rowIndex,:) = nchoosek(B(ib,:),2);
C(rowIndex,:) = A(ib);
end
% Find and remove any rows with zeros in D
idxToRemove = any(D==0,2);
C(idxToRemove,:) = [];
D(idxToRemove,:) = [];
JL on 14 Sep 2019
Thank you very much! :)