find possible combinations of each row of matrix and allocate their respective values into 2 different matrices
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
the cyclist
am 11 Sep. 2019
Should the last row of D actually be [3 4]?
How do you want to handle repeated elements in a row of B? For example, what if
B = [2 3 0
2 3 3]
Akzeptierte Antwort
the cyclist
am 11 Sep. 2019
Bearbeitet: the cyclist
am 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,:) = [];
3 Kommentare
the cyclist
am 12 Sep. 2019
I messed up the definition of the row indexing. I corrected the code above.
Also, the code will use memory more efficiently if you remove any rows of B in which the whole column is zero.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!