Find sequence of numbers in vector
조회 수: 11 (최근 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에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!