Homework Help: What did I do wrong?

1 visualizzazione (ultimi 30 giorni)
William Dowden
William Dowden il 2 Mar 2021
Commentato: Steven Lord il 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!

Risposte (1)

Jan
Jan il 2 Mar 2021
Modificato: Jan il 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 Commenti
William Dowden
William Dowden il 2 Mar 2021
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 il 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!

Accedi per commentare.

Categorie

Scopri di più su Programming in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by