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]
JL
JL 2019 年 9 月 11 日
there's no repeat of the same number

サインインしてコメントする。

採用された回答

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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by