Find sequence of numbers in vector

26 views (last 30 days)
Dobs
Dobs on 9 Nov 2021
Commented: David Hill on 9 Nov 2021
Hi,
we're supposed to find a specific sequence of numbers in a vector using a for and while loop but I don't know how to do it:
"Count the number of times that the sequence 01 occurs in the vector. Find out at which index the sequence 01 has occurred for the 8th times. Try to use the Matlab command for for one of the problems and the Matlab command while for the other problem. For the while-loop make sure that no errors can occur if there is no sequence 01 in the vector a."
This is the vector btw: a = round(rand(1000,1))
This is what I got so far but it doesn't work. Does anybody have any idea on how to do it?
Many thanks,
Debbie
clear;
clc;
a = round(rand(1000,1));
b = (0:1);
for n = 1:length(a)
strfind (a, b);
end
Error using strfind
Input strings must have one row.

Answers (2)

Jon
Jon on 9 Nov 2021
Edited: Jon on 9 Nov 2021
Rather than using strings you can check a condition involving the numerical value of the elements in a, something like
if a(k) == 0 && a(k+1)==1
... do something here
end
This will need to be in some kind of a loop to increment the index k and go through all of the elements, be careful to only go up to the second to the last element in the loop otherwise a(k+1) will be past the end of your vector which will cause an error
By the way, although it is not in your assigment, for future reference you can count the number of occurence of 01 in MATLAB using just one line of code:
count = sum(diff(a)==1)
That's the real power of MATLAB

David Hill
David Hill on 9 Nov 2021
for-loop
%for loop
a = round(rand(1000,1));
count=0;
eidx=[];
for m=1:length(a)-1
%look at what this does a(m)==0&&a(m+1)==1
%use break command once you get to 8 indexes
end
while loop
%while loop
a = round(rand(1000,1));
count=0;
eidx=[];
m=1;
while count<8&&m<length(a)-1
%similar here
end
  2 Comments
David Hill
David Hill on 9 Nov 2021
a = round(rand(1000,1));
count=0;
eidx=[];
m=0;
while count<8 && m<length(a)-1
m=m+1;
if a(m)==0&&a(m+1)==1
count=count+1;
end
end
if count==8
eidx=m-1;
end

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!