Split a vector into multiple vectors based on a value in the original vector

13 Ansichten (letzte 30 Tage)
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 Kommentar
Stephen23
Stephen23 am 2 Mär. 2016
Bearbeitet: Stephen23 am 2 Mär. 2016
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.

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Star Strider
Star Strider am 2 Mär. 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)
Jos (10584) am 2 Mär. 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)

Andrei Bobrov
Andrei Bobrov am 2 Mär. 2016
Bearbeitet: Andrei Bobrov am 2 Mär. 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'});

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by