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

8 ビュー (過去 30 日間)
Ame Michael
Ame Michael 2018 年 4 月 25 日
コメント済み: Stephen23 2018 年 4 月 25 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by