MATLAB: How to loop until the user types a specific word?

2 次查看(过去 30 天)
Say I want to repeatedly ask a user what their favourite color is. I want to keep looping this statement, and have the user type their favorite color in. But, I want to exit this loop when the user types the word, "quit." How can I achieve this?
I have been looking at using while loops, but it says the matrix dimensions do not agree. Any help would be greatly appreciated. Thank you.
  1 个评论
Stephen23
Stephen23 2018-4-25

Use strcmp to test if words match or not:

str = '';
while ~strcmp(str,'quit')
    ...
    str = input('...','s');
end

Do not use == for testing if char vectors are the same: == performs an element-wise comparison, so just like any other element-wise operation both inputs must be the same size or one of them a scalar. In any case, using strcmp is the correct tool for the job.

请先登录,再进行评论。

采纳的回答

Sigurd Askeland
Sigurd Askeland 2018-4-25
This code should do the trick:
response = '';
counter = 1;
%While loop runs until the string comparison finds
%that the response is equal to 'quit'.
while(~strcmp(response, 'quit'))
response = input('What is your favorite color? (type quit to exit) ', 's');
favorite_colors{counter} = response
counter = counter + 1;
end
%Remove quit.
favorite_colors = favorite_colors(1:end - 1)
disp 'Thank you!'

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by