Homework Help: What did I do wrong?

1 visualización (últimos 30 días)
William Dowden
William Dowden el 2 de Mzo. de 2021
Comentada: Steven Lord el 2 de Mzo. de 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!

Respuestas (1)

Jan
Jan el 2 de Mzo. de 2021
Editada: Jan el 2 de Mzo. de 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 comentarios
William Dowden
William Dowden el 2 de Mzo. de 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 el 2 de Mzo. de 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!

Iniciar sesión para comentar.

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by