## Split vector every time data changes from 2 to 1

Asked by Francisco Anaya

### Francisco Anaya (view profile)

on 4 Mar 2019
Latest activity Answered by Jos (10584)

### Jos (10584) (view profile)

on 4 Mar 2019
Accepted Answer by Walter Roberson

### Walter Roberson (view profile)

I have one vector filled with 1 and 2 as follows:
Vector A:
1
1
1
1
2
2
2
1
1
2
2
1
1
1
2
2
1
1
2
2
I want to split the above vector everytime the value change the 1, then I will have:
Vector B Vector C Vector D Vector E
1 1 1 1
1 1 1 1
1 2 1 2
1 2 2 2
2 2
2
2
Thank you

### Walter Roberson (view profile)

Answer by Walter Roberson

### Walter Roberson (view profile)

on 4 Mar 2019

vectors = mat2cell(A, diff([0;find(A(1:end-1)==2 & A(2:end) == 1); length(A)]),1);

### Jos (10584) (view profile)

Answer by Jos (10584)

### Jos (10584) (view profile)

on 4 Mar 2019

Another approach:
A = [1 2 1 1 2 1 2 2 1 1 1 2 2 2 1 1 1 2].' % data
C = accumarray(cumsum([0 ; diff(A)==-1])+1, A, [], @(x) {x}) % engine
isequal(A,cat(1,C{:})) % check

### KSSV (view profile)

on 4 Mar 2019

A = [1
1
1
1
2
2
2
1
1
2
2
1
1
1
2
2
1
1
2
2] ;
idx = find(diff(A)==-1) ;
idx = [0 ; idx ;length(A)] ;
N = length(idx)-1 ;
iwant = cell(N,1) ;
for i = 1:N
iwant{i} = A(idx(i)+1:idx(i+1)) ;
end
celldisp(iwant)