Why am I coming up with an undefined function or variable on this simple temperature script?
4 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Image Analyst
on 9 Nov 2014
Try passing in a string.
temp_conversion(25, 'Farenheit')
and for robustness, use strcmpi() instead of strcmp().
2 Comments
Image Analyst
on 9 Nov 2014
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
More Answers (0)
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!