制御構文で文字列の比較ができないのはなぜですか?

if 文や switch case 文などの制御構文の条件判断部分で文字列の比較をするとエラーとなります。例えば、以下のような記述方法ではエラーとなります。
tmp = input('set "on" or "off" >', 's');
if tmp == 'on'
disp('set as on');
else
disp('set as off');
end
エラーの例:
set "on" or "off" >off
??? エラー ==> eq
行列の次元は同じである必要があります
エラー ==> Untitled at 27
if tmp == 'on'
エラー ==
行列の次元は一致しなければなりません。

 Akzeptierte Antwort

MathWorks Support Team
MathWorks Support Team am 23 Jan. 2023

0 Stimmen

"==" で文字列を比較する場合、文字列を行列としてあつかい、それぞれの要素(**番目の文字)が同じであるかを比較することになるため、両辺の文字列の長さが同じである必要があります。
文字列全体が同じであるかどうかを比較するためには strcmp 関数を使用します。今回の場合ですと、以下のようになります。
tmp = input('set "on" or "off" >', 's');
if strcmp(tmp, 'on')
disp('set as on');
else
disp('set as off');
end

Weitere Antworten (0)

Kategorien

Mehr zu 言語の基礎 finden Sie in Hilfe-Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!