Find sequence of numbers in vector
36 views (last 30 days)
Show older comments
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
0 Comments
Answers (2)
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
0 Comments
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
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
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!