Why am I coming up with an undefined function or variable on this simple temperature script?

I'm writing a very simple temperature conversion script, and keep getting the undefined error. Here is the script:
function[y] = temp_conversion(x,unit)
if strcmp(unit,'Farenheit');
y = (x - 32)*(5/9);
elseif strcmp(unit,'Centigrade');
y = (x * (9/5)) + 32;
end
When I call it in matlab using
[y] = temp_conversion(25,Farenheit)
or [y] = temp_conversion(25,Centigrade)
I will get
"undefined function or variable 'Farenheit'." or "undefined function or variable 'Centigrade'." respectively.
I feel like I am missing something very simple, and am looking for some guidance, hope to hear from you guys.

 採用された回答

Image Analyst
Image Analyst 2014 年 11 月 9 日
Try passing in a string.
temp_conversion(25, 'Farenheit')
and for robustness, use strcmpi() instead of strcmp().

2 件のコメント

To make it even more robust, just check the first character, in case people misspell it or pass in the official units name of 'Celsius' instead of Centigrade, and check for illegal units:
function y = temp_conversion(x,unit)
try
if upper(unit(1)) == 'F'
y = (x - 32)*(5/9);
elseif upper(unit(1)) == 'C'
y = (x * (9/5)) + 32;
else
warningMessage = sprintf('Error: %s is an unknown unit', unit);
uiwait(warndlg(warningMessage));
y = [];
end
catch ME
errorMessage = sprintf('Error in function %s() at line %d.\n\nError Message:\n%s', ...
ME.stack(1).name, ME.stack(1).line, ME.message);
fprintf(1, '%s\n', errorMessage);
uiwait(warndlg(errorMessage));
end
Adli
Adli 2014 年 11 月 9 日
Of course! Seems so obvious now. Thank you IA, I think you just saved me a lot of stress in the future as well.

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

その他の回答 (0 件)

製品

質問済み:

2014 年 11 月 9 日

コメント済み:

2014 年 11 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by