MATLAB: Splitting a vector up into unequal sections seperated by zeros

splitting; vector; sections; zeros

Hi everyone
I was wondering if someone could help me split up a vector into sections seperated by zeros. I have alot of data but if I give you an example with shorter data
if I have A = [ 1 2 3 0 0 0 0 0 2 3 4 0 0 0 0 0 4 5 6 7 0 0 0 0 1 1 1] and I would like section 1 = [ 1 2 3] section 2 = [ 2 3 4] section 3 = [ 4 5 6 7] section 4 = [ 1 1 1] how would I go about this?

Best Answer

This works:
A = [1 2 3 0 0 0 0 0 2 3 4 0 0 0 0 0 4 5 6 7 0 0 0 0 1 1 1];
ne0 = find(A~=0); % Nonzero Elements
ix0 = unique([ne0(1) ne0(diff([0 ne0])>1)]); % Segment Start Indices
ix1 = ne0([find(diff([0 ne0])>1)-1 length(ne0)]); % Segment End Indices
for k1 = 1:length(ix0)
section{k1} = A(ix0(k1):ix1(k1));
end
celldisp(section) % Display Results