MATLAB: Index the first maximum value in a sequence of consecutive numbers

consecutive numbers

I have a column vector with the following sequences:
x = [0,0,1,1,1,2,0,1,2,2,3,3,3,3,3,0,0,0]';
I would like a logical vector a, equalizing 1 if it is equal to the first maximum value of the particular sequence of consecutive numbers (the sequences are separated by zeros), ie:
x = [0,0,1,1,1,2,0,1,2,2,3,3,3,3,3,0,0,0]';
a = [0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0]';
The code should be as efficient as possible (No loops).

Best Answer

Without for loop:
a=zeros(1,numel(x));
idx=find([0 diff(x)~=0]);
idxx=find(x(idx)==0)-1;
a(idx(idxx))=1
Related Question