Matrix dimensions must agree while using if

5 ビュー (過去 30 日間)
Sang Heon Lee
Sang Heon Lee 2017 年 9 月 15 日
編集済み: Martin Grden 2020 年 10 月 28 日
celestialBody = input('Celestial body = ','s');
if celestialBody == 'moon'
mass1 = MASS_OF_MOON;
distance = RADIUS_OF_MOON;
elseif celestialBody == 'mercury'
mass1 = MASS_OF_MERCURY;
distance = RADIUS_OF_MERCURY;
else
mass1 = 0;
distance = 1;
end
Above is my script and whenever I run this script, type the celestialBody as mercury, it says
Matrix dimensions must agree.
Error in exoweight (line 16)
if celestialBody == 'moon'
how can I solve this error? the values for the constants are set.

採用された回答

KSSV
KSSV 2017 年 9 月 15 日
doc Strcmpi or strcmp
celestialBody = input('Celestial body = ','s');
if strcmpi('moon',celestialBody)
mass1 = MASS_OF_MOON;
distance = RADIUS_OF_MOON;
elseif strcmpi('mercury',celestialBody)
mass1 = MASS_OF_MERCURY;
distance = RADIUS_OF_MERCURY;
else
mass1 = 0;
distance = 1;
end

その他の回答 (2 件)

Jan
Jan 2017 年 9 月 15 日
The problem is in
if celestialBody == 'moon'
The == operator works elementwise. Therefore the strings on the left and the right need to have the same number of elements (or one must be a scalar character). As suggested already, use strcmp or strcmpi to compare strings.
  1 件のコメント
Martin Grden
Martin Grden 2020 年 10 月 28 日
編集済み: Martin Grden 2020 年 10 月 28 日
Maybe MATHWORKS should offer a substitute to doing string comparisons, when checking a 2-value property (for ex. timer.Running). For now, you can do:
if (timer.running(end)=='n')
...

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


Arun Kumar Misra
Arun Kumar Misra 2017 年 9 月 15 日
編集済み: Arun Kumar Misra 2017 年 9 月 15 日
try this it works
celestialBody = input('Celestial body = ','s');
if strcmp(celestialBody,'moon')
mass1 = MASS_OF_MOON;
distance = RADIUS_OF_MOON;
elseif strcmp(celestialBody,'mercury')
mass1 = MASS_OF_MERCURY;
distance = RADIUS_OF_MERCURY;
else
mass1 = 0;
distance = 1;
end

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by