Split the long vector into shorter ones

Hi!
I have a long vector that I want to split into the shorter ones. The vector contains only ones and zeros. I would like to split the vector from 1 to the next 1 (and not including this 1). For example, I have a 17x1 vector A = [1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0] . I want to split it into smaller ones. So in the end I would like to have: В = [1 0 0 0], С = [1 0 0 0 0], D = [1 0 0 0 0 0], E = [1 0]. How can I do it?
Thanks a lot fot any help!

 Accepted Answer

Ameer Hamza
Ameer Hamza on 20 May 2020
Edited: Ameer Hamza on 20 May 2020
Try this
A = [1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0];
groups = cumsum(A);
B = splitapply(@(x) {x}, A, groups);
It creates a cell array with split arrays. This link show why you should avoid naming variables B, C, D, .. : https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval

5 Comments

Thanks a lot! It works. And what should I do if I want to split other columns in the matrix based on the same thing? I mean I have also other columns in the matrix, so I want to split it into the smaller ones based on the 1 or 0 number in my vector A. So the vector A is one of the columns inside a bigger matrix. Sorry if I explained it a bit confusing :)
Can you share the format of your matrix A? What is its shape? How do you want to distribute each column? Can you give an example using a small matrix?
Yes, sure! So the matrix has the size of 8 columns and 9000 rows. The 8th column is the vector I was asking about, so it contains these zeros and ones. If I have 1 in this vector and then zeros and then 1 again, I want the whole matrix to be splitted from 1 to next 1.
Following will work if A is the matrix with last column 0 and 1.
groups = cumsum(A(:,end));
B = splitapply(@(x) {x}, A, groups);
Yes, it works! Thank you so much!!!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!