Split a matrix into smaller matrices based on another variable

1 view (last 30 days)
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!

Accepted Answer

Ameer Hamza
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)).';

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!