MATLAB Answers

Homework Help: What did I do wrong?

20 views (last 30 days)
William Dowden
William Dowden on 2 Mar 2021
Commented: Steven Lord on 2 Mar 2021
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!

Answers (1)

Jan
Jan on 2 Mar 2021
Edited: Jan on 2 Mar 2021
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 Comments
Steven Lord
Steven Lord on 2 Mar 2021
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!

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!