MATLAB: Dividing a column matrix based on the no

division of matrixregexpsequencesplit

i have a single column matrix A=0 0 0 1 1 1 1 0 0 0 0 2 2 2 2 0 0 0 0 now i have to divide this in to several matrices such whenever 0 changes to 1 or 2 i want a new matrix in this case A1= 1 1 1 1 0 0 0 0; A2=2 2 2 2 0 0 0 0 which are also single column matrices

Best Answer

A = [0 0 0 1 1 1 1 0 0 0 0 2 2 2 2 0 0 0 0].';
Split sequence (transforming in string)
out = regexp(sprintf('%d',A) ,'(1+0+|2+0+)','match');
Convert to double and store in cell array
c = cellfun(@(x) x.'-'0',out,'un',0)
c{1} % to retrieve the value

Organize eventually in structure with dynamic fields A001, A002, ..., An
numC = numel(c);
s = cell2struct(c, reshape(sprintf('A%03d', 1:numC),4,[]).',numC);
s.A001 % to retrieve the value
EDITED
With a loop
A = [0 0 0 1 1 1 1 0 0 0 0 2 2 2 2 0 0 0 0].';
c = 0;
s = 0;
% Start condition
if ismembc(A(1,1),1:2)
s = 1;
end
for n = 2:numel(A(:,1))-1
if A(n,1) == 0 && ismembc(A(n+1,1),1:2)
if s
c = c+1;
Out{c} = A(s:n,:);
end
s = n+1;
end
end
% End condition
if s < n
Out{c+1} = A(s:end,:);
end