# Split a matrix into smaller matrices based on another variable

2 views (last 30 days)
Daria Ivanchenko on 21 Oct 2020
Commented: Ameer Hamza on 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!

Ameer Hamza on 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 CommentsShow 1 older commentHide 1 older comment
Ameer Hamza on 21 Oct 2020
I am glad to be of help!