I have this code:
function CalcParkingRates()
prompt='Days of stay: ';
days=input(prompt);
prompt='Hours of stay: ';
hours=input(prompt);
prompt='Minutes of stay: ';
minutes=input(prompt);
ValidateTime(days, hours, minutes);
LongTerm(validDays, validHours);
ShortTerm(validDays, validHours, validMinutes);
end
function [validDays, validHours, validMinutes]=ValidateTime(days, hours,...
minutes)
totalminutes=(days*24*60)+(hours*60)+minutes;
validDays=floor(totalminutes/1440);
validHours=floor((totalminutes-(validDays*24*60))/60);
validMinutes=totalminutes-(validDays*24*60)-(validHours*60);
fprintf('Simplified stay is %d days, %d hours, %d minutes \n', validDays,...
validHours, validMinutes)
end
but when I run the CalParkingRates function, it just says:
Undefined function or variable 'validDays'
Error in CalcParkingRates (line 9)
ValidateTime, LongTerm and ShortTerm are functions that I know work and have tested. Does anyone know why it isn't recognizing variable that I define in a helper function?

回答 (1 件)

dpb
dpb 2013 年 10 月 15 日
編集済み: dpb 2013 年 10 月 15 日

1 投票

You didn't return the outputs of ValidateTime to any variables when called so the local values within are lost. Matlab does NOT modify argument variables (but the variable names aren't correctly matched even if it did so). Also, Matlab functions have local scope of any and all variables that are not explicitly GLOBAL (excepting for nested functions, of course, which are fully contained in the scope of the previous function and hence share variables with those in the containing function).
You need to call the function as
[validDays, validHours, validMinutes]=ValidateTime(days, hours,minutes);
You'll also then need return variables for the outputs of the [Long|Short]Term functions to get their values back to the calling function as well.

カテゴリ

ヘルプ センター および File Exchange で Variables についてさらに検索

質問済み:

2013 年 10 月 14 日

編集済み:

dpb
2013 年 10 月 15 日

Community Treasure Hunt

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

Start Hunting!

Translated by