Why is my function not recognized?
27 次查看(过去 30 天)
显示 更早的评论
Greetings! I've written the following MATLAB script:
CorrectAnswers=['B' 'D' 'A' 'A' 'C' 'B' 'D' 'A' 'C' 'B'];
%These are the correct answers for a quiz. There are ten questions on the quiz.
Claire=['B' 'D' 'A' 'A' 'C' 'B' 'D' 'A' 'C' 'B'];
Oliver=['A' 'C' 'A' 'A' 'C' 'B' 'D' 'A' 'C' 'A'];
Lana=['B' 'D' 'B' 'A' 'C' 'B' 'D' 'B' 'C' 'B'];
Abbie=['B' 'B' 'A' 'C' 'C' 'B' 'D' 'A' 'D' 'B'];
Kevin=['B' 'D' 'A' 'A' 'D' 'B' 'D' 'A' 'C' 'B'];
%These are the answers five different students gave.
function [StudentScore]=CheckScore(StudentAnswers)
StudentScore=0;
for k=1:10
if StudentAnswers(k)==CorrectAnswers(k)
StudentScore=StudentScore+10;
end
end
disp(StudentScore)
end
%The above function checks if a student's answers match the correct
%answers, which are defined in the vector "CorrectAnswers". The score
%increases by 10 for each matching answer.
When writing, I received the following error in the script file: "Line 11: Function might be unused." For reference, Line 11 is shown below:
function [StudentScore]=CheckScore(StudentAnswers)
When I go to the Command Window to call the function "CheckScore", like below, this is the result:
>> CheckScore(Oliver)
Unrecognized function or variable 'CheckScore'.
I'm not sure why "CheckScore" is undefined, when I (think I) defined it as a for loop within the function code. I feel like there's a very simple fix for this, but I can't for the life of me figure it out. Any help is appreciated, and thank you for your time!
0 个评论
采纳的回答
Govind KM
2024-10-3
编辑:Govind KM
2024-10-3
Hi Ny,
If a function is defined inside of a MATLAB script containing other code, it becomes a local function and can only be called inside of the script itself. This is why the CheckScore function is unrecognized when called in the command window outside of the script.
To create a function that can be called in the command window or in other scripts, move the code for the CheckScore function to a new .m file with the same name as the function (i.e. CheckScore.m), and save it either in the current folder or in a folder on the MATLAB search path. More details on function creation can be found in the documentation below:
Hope this is helpful!
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!