Clear Filters
Clear Filters

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

2 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 25 Apr 2018

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.

Sign in to comment.

Accepted Answer

Sigurd Askeland
Sigurd Askeland on 25 Apr 2018
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!'

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!