where is the mistake?
조회 수: 1(최근 30일)
표시 이전 댓글
function oo(w)
if isstring(w)
count =0;
while count<15
if strcmp(w(count),'r')
disp('yes')
count=count+1;
end
end
end
댓글 수: 0
답변(3개)
David Hill
2022년 1월 25일
Why not just:
w='abcderfrgrhhr';
l=w=='r'
l =
1×13 logical array
0 0 0 0 0 1 0 1 0 1 0 0 1
댓글 수: 0
VBBV
2022년 1월 25일
편집: VBBV
2022년 1월 25일
while count<15
if strcmp(w(count),'r')
disp('yes')
count=count+1;
else
break;% this will exit from while
end
end
Given while condition is good when the count is incremented continuously inside if statement for given input string. If you provide input string such that it doesn't enter if statement then your program becomes frozen without further increment of count variable.
댓글 수: 2
VBBV
2022년 1월 25일
function oo(w)
if isstring(w)
count =0;
while count<15
if strcmp(w(count),'r')
disp('yes')
count=count+1;
else
break;% this will exit from
end
end
end % end if
end % end function
Complete closing end for function and if statements
DGM
2022년 1월 25일
편집: DGM
2022년 1월 25일
If you want it to do what your code implies:
w = 'a4jkltr6mramlkrffgajr';
oo(w)
function oo(w)
if isstring(w) % strings are not chars
w = char(w);
end
if ischar(w)
for c = 1:numel(w) % don't use a while loop, don't hard-code variable length
if w(c) == 'r' % don't need strcmp for single char tests
disp('yes') % if all you print is 'yes'
else
disp('no') % then there's no way to know where it occurred
end
end
end
end
If instead you want a function that's actually useful for something, @David Hill already posted a useful answer.
w = 'a4jkltr6mramlkrffgajr';
idx = letterisr(w)
function out = letterisr(w) % use a meaningful name and provide output
if isstring(w) % strings are not chars
w = char(w);
end
if ischar(w)
out = w == 'r';
end
end
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!