Using text as condition in a while loop

强颜欢笑 提交于 2019-12-11 03:24:29

问题


Im having some trouble with using text as an condition for a while loop, currently the basic coding is:

result=struct('val','yes');

while result.val=='yes'
result.val=input('more digits?');
end

So as you see, what Im trying to do is keeping the loop going as long as the user types in 'yes'. But thats one of the probelmes I am having; Is there a way to get rid of the need to write the ''(e.g yes instead of 'yes')? Secondly, when I run the code it gives me the error message "Error using == ,Matrix dimensions must agree.". I realise this have to do with the word yes being longer than no, but I don't know how to fix it. It's not really an issue though considering its the the program ends anyway, but it is an annoyance I would like to get rid off.


回答1:


To compare strings, use strcmp, or strcmpi to ignore case. It will handle comparison of different length strings. For example:

strcmpi(result.val,'yes')

If you want to search for a substring, such as just a 'y', at the beginning of the input, consider strncmpi (strncmpi(result.val,'y',1)) or just check the first character (result.val(1)).



来源:https://stackoverflow.com/questions/19984833/using-text-as-condition-in-a-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!