Homework Help: What did I do wrong?

14 次查看(过去 30 天)
My code works as intended, except when I input "kmpl", it displays the error shown below. What can I do to resolve this? Also, are there any simplifications I can make to my code? I feel like it can be optimized. Thanks!

回答(1 个)

Jan
Jan 2021-3-2
编辑:Jan 2021-3-2
The == operator compares its arguments elementwise. If they have a different number of elements, this fails, except it one is a scalar.
Solution: Compare char vectors with strcmp:
if strcmp(Units, 'mpg')
disp(x)
elseif strcmp(Units, 'kmpl')
disp(y)
end
If you post your code as text, the readers could post some improvements by copy&paste. The screenshot forces us to retype your code again.
Instead of creating x and y, it is more efficient to define only the string, which is used.
NUM2STR calls SPRINTF internally, so you can omit it, if it is an argument of SPRINTF.
Instead of creating a char which is used as input of DISP, you can write directly by FPRINTF:
if strcmp(Units, 'mpg')
fprintf('Your fuel economy is %g mile per gallon\n', mpg);
elseif strcmp(Units, 'kmpl')
fprintf('Your fuel economy is %g km per liter\n', kmpl);
end
  2 个评论
William Dowden
William Dowden 2021-3-2
Thank you very much! I appreciate you taking the time to answer my question! I hope you have a great day!
Steven Lord
Steven Lord 2021-3-2
Another approach, if you have a relatively small number of allowed options, would be switch and case.
a = {'apple', 'banana', 'cherry'};
for whichFruit = 1:numel(a)
f = a{whichFruit}
switch f
case 'apple'
disp('You gave me an apple!')
case 'cherry'
disp('You gave me a cherry!')
otherwise
disp('I don''t know what fruit you gave me!')
end
end
f = 'apple'
You gave me an apple!
f = 'banana'
I don't know what fruit you gave me!
f = 'cherry'
You gave me a cherry!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by