Find sequence of numbers in vector
13 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Jon
2021-11-9
编辑:Jon
2021-11-9
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 个评论
David Hill
2021-11-9
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 个评论
David Hill
2021-11-9
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!