フィルターのクリア

How to make Matlab give different answers for different text inputs of different lengths

1 回表示 (過去 30 日間)
A = input('Ask me anything: ','s');
if A==('Are you sentient?')
disp('Yes')
else
disp('Ask me anything but that')
end
This only works if I ask "Are you sentient?", or input a sentence of equal length. So if I input "abc def ghijklmno" It'll take it and give the else answer, but if I simply ask it "Yes?" it gives me the error, "Arrays have incompatible sizes for this operation" What am I doing wrong?

採用された回答

Stephen23
Stephen23 2023 年 8 月 16 日
編集済み: Stephen23 2023 年 8 月 16 日
"What am I doing wrong?"
You are using EQ (i.e. ==) for character arrays, which performs a character-by-character comparison (exactly like using EQ on numeric arrays). If you want to compare the entire text use STRCMP, STRCMPI, or similar:
if strcmpi(A,'Are you sentient?')
  2 件のコメント
Stephen23
Stephen23 2023 年 8 月 16 日
編集済み: Stephen23 2023 年 8 月 16 日
Note how EQ works for character arrays:
'cat' == 'hat'
ans = 1×3 logical array
0 1 1
which is just like EQ for numeric arrays:
[1,2,3] == [0,2,3]
ans = 1×3 logical array
0 1 1
This operation only works if the array sizes are compatible:
(which yours are not, as you noted yourself)
Noah Cross
Noah Cross 2023 年 8 月 16 日
Nice, that makes sense. Thanks for the answer.

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

その他の回答 (2 件)

DGM
DGM 2023 年 8 月 16 日
編集済み: DGM 2023 年 8 月 16 日
I figured that for multiple cases, it would be neater to use a switch-case.
A = input('How do you eat your oatmeal?: ','s');
switch lower(A)
case 'hot'
disp('Wow! Me too! We have so much in common.')
case 'cold'
disp('That''s kind of gross.')
case {'with my mouth','with a spoon'} % you can use grouped cases
disp('Ha ha, mister funny man.')
otherwise
disp('I didn''t expect you to say that')
end

Chunru
Chunru 2023 年 8 月 16 日
A = input('Ask me anything: ','s');
if strcmpi(A, 'Yes') % compare string (case insensitive)
disp('Yes')
else
disp('Ask me anything but that')
end

カテゴリ

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

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by