Why is my function not recognized?
64 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Govind KM
on 3 Oct 2024
Edited: Govind KM
on 3 Oct 2024
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!
2 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!