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

조회 수: 1 (최근 30일)
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
the cyclist
the cyclist 2019년 9월 11일
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]

댓글을 달려면 로그인하십시오.

채택된 답변

the cyclist
the cyclist 2019년 9월 11일
편집: the cyclist 2019년 9월 12일
% 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
the cyclist
the cyclist 2019년 9월 12일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by