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

8 visualizaciones (últimos 30 días)
Ame Michael
Ame Michael el 25 de Abr. de 2018
Comentada: Stephen23 el 25 de Abr. de 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 comentario
Stephen23
Stephen23 el 25 de Abr. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Sigurd Askeland
Sigurd Askeland el 25 de Abr. de 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!'

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by