Indexing a vector within a bigger one in MATLAB

  • A+
Category:Languages

I'm trying to find the index position of the smaller vector inside a bigger one.

I've already solved this problem using strfind and bind2dec, but I don't want to use strfind, I don't want to convert to string or to deciamls at all.

Given the longer vector

a=[1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,0,0,0,0,1,1]; 

I want to find the index of the smaller vector b inside a

b=[1,1,1,0,0,0]; 

I would expect to find as result:

result=[15,16,17,18,19,20]; 

Thank you

 


Solution with for loops:

a=[1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,0,0,0,0,1,1]; b=[1,1,1,0,0,0]; c = []; b_len = length(b) maxind0 = length(a) - b_len + 1 %no need to search higher indexes   for i=1:maxind0   found = 0;   for j=1:b_len     if a(i+j-1) == b(j)       found = found + 1;     else       break;     end   end    if found == b_len  % if sequence is found fill c with indexes     for j=1:b_len       c(j)= i+j-1;     end      break   end end  c %display c 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: