Split a matrix into smaller matrices based on another variable

1 次查看(过去 30 天)
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
Ameer Hamza 2020-10-21
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)).';

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by