Split a matrix into smaller matrices based on another variable
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Daria Ivanchenko
il 21 Ott 2020
Commentato: Ameer Hamza
il 21 Ott 2020
Hi!
I have two variables, the size of each of them is 50x15179, one of them (A) insludes some specific numbers, the other one (B) has only zeros and ones in it. I want to divide the first variable A into smaller matrices (or cells) based on the appearance of ones in the variable B. How can I do this?
Just as an example,
A = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5];
B = [1 0 1 0 0; 1 0 1 0 0; 1 0 1 0 0; 1 0 1 0 0; 1 0 1 0 0];
I want to get two separate matrices like:
C = [1 2; 1 2; 1 2; 1 2; 1 2];
D = [3 4 5; 3 4 5; 3 4 5; 3 4 5; 3 4 5;]
Thank you!
0 Commenti
Risposta accettata
Ameer Hamza
il 21 Ott 2020
If you have multiple 1s in a row of your B matrix, then creating variable names like C, D, .. is not advisible: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. It is better to use cell arry.
Try the following code
A = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5];
B = [1 0 1 0 0; 1 0 1 0 0; 1 0 1 0 0; 1 0 1 0 0; 1 0 1 0 0];
grps = cumsum(B, 2);
C = cell(size(A,1),1);
for i = 1:numel(C)
C{i} = splitapply(@(x) {x}, A(i,:), grps(i,:));
end
If number of 1s are equal in each row then you can also run the following
C = reshape([C{:}], [], numel(C)).';
2 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrices and Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!