Split the long vector into shorter ones

3 vues (au cours des 30 derniers jours)
Daria Ivanchenko
Daria Ivanchenko le 20 Mai 2020
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!

Réponse acceptée

Ameer Hamza
Ameer Hamza le 20 Mai 2020
Modifié(e) : Ameer Hamza le 20 Mai 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 commentaires
Ameer Hamza
Ameer Hamza le 20 Mai 2020
Following will work if A is the matrix with last column 0 and 1.
groups = cumsum(A(:,end));
B = splitapply(@(x) {x}, A, groups);
Daria Ivanchenko
Daria Ivanchenko le 21 Mai 2020
Yes, it works! Thank you so much!!!

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