Why is my function not recognized?

조회 수: 79 (최근 30일)
Ny
Ny 2024년 10월 3일
편집: Govind KM 2024년 10월 3일
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!

채택된 답변

Govind KM
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!
  댓글 수: 2
Ny
Ny 2024년 10월 3일
Hi Govind,
This helped a lot and I was able to fix the issue! Thank you for your time!
Govind KM
Govind KM 2024년 10월 3일
편집: Govind KM 2024년 10월 3일
Glad to help! :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by