MATLAB: Need a method to arrange data

data arrangeMATLAB

How can i arrange a array a = [1 2 3 4 3 4 5 3 3 4 2 3 3 4 1 2 3 3 4];
here the numbers 1 ,2 ,…are the order or level in the hierarchy , 1 is top level. 2 is below 1 , 3 is below level 2 and so on.
from first occurence of 1 till next is 1 group of data .
Now i need to arrange array a into array b like this : b =[4 3 5 4 3 3 4 3 2 3 4 3 2 1 3 4 3 2 1];
here tree is like this for data from first 1 till next 1 in array a, i.e.: 1 2 3 4 3 4 5 3 3 4 2 3 3 4
1{
2{
3{
4{
} first 2 elements in array b are 4 ,3 from this part of tree.
}
3{
4{
5{
} next 3 elements in b are 5 ,4, 3 ,and so on..
}
}
3{
}
3{
4{
}
}
}
2{
3{
}
3{
4{
}
}
}
}

Best Answer

I am sure there is a more efficient way to do this, but I cannot see it right off.
I = find(a==1);
b = [];
for ii = 1:length(I)
if length(I)>=ii+1
A = a(I(ii):I(ii+1));
else
A = [a(I(ii):end) 1];
end
B = [];
D = [1 diff(A)];
cnt = 1;
while any(D<=0)
L = find(D<=0,1,'first');
L2 = L;
X = A(L);
Y = X+1;
while Y>X
Y = A(L-1);
B(cnt) = Y;
cnt = cnt + 1;
L = L-1;
end
A(L:L2-1) = [];
D = [1 diff(A)];
end
b = [b B];
end
b