# Find sequence of numbers in vector

34 ビュー (過去 30 日間)
Dobs 2021 年 11 月 9 日
コメント済み: David Hill 2021 年 11 月 9 日
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.

サインインしてコメントする。

### 回答 (2 件)

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 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

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 件のコメント表示非表示 1 件の古いコメント
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

サインインしてコメントする。

R2021b

### Community Treasure Hunt

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

Start Hunting!