フィルターのクリア

Reading user input when input is a combination of letters?

27 ビュー (過去 30 日間)
Stenila  Simon
Stenila Simon 2017 年 11 月 11 日
コメント済み: Alishba Zafar 2020 年 8 月 5 日
I'm writing an mfile that asks the user to input different letter codes (for example, ABC or BAC or CBA, etc), and depending on that letter combination, go to different functions or mfiles or do different things. How would I be able to read that in matlab? Below is basically what I'm doing so far:
prompt = 'Please input letter code:';
inp = input(prompt);
if inp == CBA
fprintf('answer is 1');
elseif inp == BAC
fprintf('answer is 0');
end
etc. But when I run something like this on MATLAB, it is giving me an error when the letters are input, saying " undefined function or variable BAC", etc. How can I avoid this happening and actually make matlab read the letter inputs?

回答 (1 件)

David Goodmanson
David Goodmanson 2017 年 11 月 13 日
Hi Stenila,
You need to get the user input as a string using the 's' option, not the usual input. Right now Matlab thinks that BAC must be the name of a function or variable, as it says. Once inp is a string you can compare it to 'BAC' :
prompt = 'Please input letter code:';
inp = input(prompt,'s');
if strcmp(inp,'CBA')
fprintf('answer is 1');
elseif strcmp(inp,'BAC');
fprintf('answer is 0');
end
If you want a case-insensitive string comparison, use strcmpi.
  2 件のコメント
Ralph Segi
Ralph Segi 2019 年 6 月 24 日
Thank you, it helped me! :-)
Alishba Zafar
Alishba Zafar 2020 年 8 月 5 日
Please tell me about user dependent character choice??

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by