Effacer les filtres
Effacer les filtres

Split a matrix into smaller matrices based on another variable

2 vues (au cours des 30 derniers jours)
Daria Ivanchenko
Daria Ivanchenko le 21 Oct 2020
Commenté : Ameer Hamza le 21 Oct 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!

Réponse acceptée

Ameer Hamza
Ameer Hamza le 21 Oct 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 commentaires
Daria Ivanchenko
Daria Ivanchenko le 21 Oct 2020
Thank you very much!
Ameer Hamza
Ameer Hamza le 21 Oct 2020
I am glad to be of help!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by