how to stop while statement
11 ビュー (過去 30 日間)
古いコメントを表示
function isitalike=comparestrings(a,b)
n=length(a);
m=length(b);
c=logical(0);
y=m;
z=n;
f=0;
if m>n
temp=a;
a=b;
b=temp;
end
for i=1:n
c=strcmp(a(i),b(1))
if c
j=1;
if a(i:n)>=length(b)
for k=1:length(b)
while a(i)==b(j)
if j==length(b)
if z>y
disp('b is in a')
f=1;
else
disp('a is in b')
f=1;
end
end
j=j+1;
i=i+1;
end
end
end
end
end
if f==0
if z>y
disp('b is not in a')
else
disp('a is not in b')
end
end
The function above does not work properly I can't stop the while statement after i have found that a is in b or b is in a. This is what happens:
>> a
a =
agg
>> b
b =
sagggsa
>> comparestrings(a,b)
c =
0
c =
1
a is in b
??? Attempted to access b(4); index out of bounds because
numel(b)=3.
Error in ==> comparestrings at 39
while a(i)==b(j)
>>
0 件のコメント
採用された回答
Walter Roberson
2011 年 11 月 7 日
What is your statement
if a(i:n)>=length(b)
intended to mean?
Your while loop continues indefinitely because you do not have an condition defined to escape from it with a "break" statement.
3 件のコメント
Walter Roberson
2011 年 11 月 7 日
a(i:n) selects position i, i+1, i+2, .... n out of "a", giving a vector as a result as long as n >= i+1
You then compare those _characters_ to the length of b. That is going to generally give you a vector result, one value for each of the characters.
When you have a vector as the thing being tested in an "if" statement, the "if" is considered true only if _all_ of the elements of the vector are non-zero (true).
If you wanted to compare the _length_ of the rest of a, you could use
if length(a(i:n)) >= length(b)
Have another loop at the structure of your "while" statement. It is of the form
while a(i) == b(j)
if THAT %if #1
if THE_OTHER %if #2
else
end %end of if #2
end %end of if #1
i=i+1; j=j+1;
end %end of while
Notice there is no breaking out of the loop within the body of the loop, so the loop would only stop if it found an a(i) which was not equal to b(j) . However, if the two strings were the same right up to the end of one of them, you are going to increment i or j to point past the end of the "a" or "b" string (or both), resulting in the index out of range error you saw.
Remember, an outer "if" or "while" only affects whether you start an inner loop or not. Once you are within the inner loop, you stay within that loop until the conditions for that loop are satisfied, even if you change variables so completely that the condition of some outer loop or "if" was violated.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Dialog Boxes についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!