Split a vector into multiple vectors based on a value in the original vector
Afficher commentaires plus anciens
Please, I would like to split a vector into multiple vectors. For example a vector [2 0 5 7 0 14 0 17 19 20] should be split using the 0 in it as a delimiter to obtain
a1 = [2].... a2 = [5 7]...... a3 = [14]....... a4 = [17 19 20].
I would be very grateful. Thanks
1 commentaire
Note that it is a really bad code to create lots of separate variables dynamically. Although beginners love doing this, in fact it is a slow, buggy, and obfuscated way to write code. Read this to know why:
Instead you should simply put all of the output vectors into one cell array.
Réponses (3)
Star Strider
le 2 Mar 2016
One approach:
V = [2 0 5 7 0 14 0 17 19 20];
idx = [find(V == 0) length(V)+1]; % Find Zeros & End Indices
didx = diff([0 idx])-1; % Lengths Of Nonzero Segments
V0 = V; % Create ‘V0’ (Duplicate Of ‘V’)
V0(V0 == 0) = []; % Delete Zeros
C = mat2cell(V0, 1, didx); % Create Cell Array
Result = C(cellfun(@(x) size(x,2)~=0, C)); % Delete Empty Cells
It’s a bit more complicated here than it needs to be for your vector, because I also designed it to be robust to leading and trailing zeros as well, even though your vector doesn’t have them.
I did not assign them as ‘a1’ ... ‘a4’ because creating dynamic variables is poor programming practise. They are instead elements of the ‘Result’ cell array.
If you have a specific reason to refer to an element of ‘Result’ as a particular variable, ‘a4’ would be:
a4 = Result{4}
a4 =
17 19 20
Jos (10584)
le 2 Mar 2016
V = [0 2 0 0 5 7 0 14 0 0 0 17 19 20]
tf = V==0
ix = cumsum(tf & [true diff(tf) > 0])
Result = arrayfun(@(k) V(ix==k & ~tf),1:ix(end),'un',0)
1 commentaire
Amir Pasha Zamani
le 12 Sep 2020
Great job Genius :)
THANKS
Andrei Bobrov
le 2 Mar 2016
Modifié(e) : Andrei Bobrov
le 2 Mar 2016
V = [0 2 0 0 5 7 0 14 0 0 0 17 19 20];
V0 = V(:)';
i0 = diff(strfind([0,V0,0],0));
out = mat2cell(V0(V0 ~= 0),1,i0(i0 > 1) - 1);
or with bwlabel from Image Processing Toolbox
x = bwlabel(V(:));
t = x ~= 0;
out = accumarray(x(t),V(t),[],@(x){x'});
Catégories
En savoir plus sur MATLAB dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!