Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)
Ame Michael
Ame Michael le 25 Avr 2018
Commenté : Stephen23 le 25 Avr 2018
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 commentaire
Stephen23
Stephen23 le 25 Avr 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.

Connectez-vous pour commenter.

Réponse acceptée

Sigurd Askeland
Sigurd Askeland le 25 Avr 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!'

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by