MATLAB: Create index between values

indexMATLAB

Hi,
I have a 5 x 1 array, a = [ 0 1 0 2 0]. (this is a generalization of a larger problem)
I want create and index that fills all the values starting with 1, and ending at the last occurance of the number 2 (that does not have another 1 in between)?
I want to create b = [0 1 1 1 0].
I can do:
b = zeros(1,length(a))
b(strfind(a, [1]):strfind(a, [2])) = 1
That works for that specific case.
But, what if I have a = [ 0 1 0 2 0 2 1]? I want to create b = [0 1 1 1 1 1 0].
Any help woudl be appreciated! Thanks!
Inna

Best Answer

Study this
%%

a = [0,1,0,2,0,2,1];
ixb = find( a==1, 1,'first'); % begin
ixe = find( a==2, 1,'last'); % end
%%
b = zeros(size(a));
b(ixb:ixe)=1;
b contains the result
>> b
b =
0 1 1 1 1 1 0