I need help with using a function file for assinging letter grades.

I'm using a fuction file to transport inputs of numerical grades into output letter grades.
Here are my two scripts
%Script 1: A1_3_8.m
%Problem 3.8A
format compact
score=input('Enter numerical grade:');
grade= lettergrade(score);
disp(grade);
%Script 2: lettergrade.m
format compact
function grade= lettergrade(score)
array=['A','B','C','D','F'];
if score < 0 || score > 100
disp('Invalid')
elseif score >= 90
grade=array(1);
elseif score >= 80
grade=array(2);
elseif score >= 70
grade=array(3);
elseif score >= 60
grade=array(4);
else
grade=array(5);
end
end
------------------------------------------------------------
I am not sure of what I am doing and need help with using a function file properly.

回答(1 个)

format compact
function grade= lettergrade(score)
When you have an executable line before the first function line, then that makes the file a script file rather than a function file. script files cannot be called as functions, such as your
grade= lettergrade(score);
Also, there is a restriction that a script file cannot have a function with the same name as the script -- so function lettergrade cannot be inside script file lettergrade.m
format statements are not needed in every file: the last format executed is obeyed until you execute another format or quit MATLAB. You especially do not need a format statement inside code that does not display any output.

类别

帮助中心File Exchange 中查找有关 Entering Commands 的更多信息

产品

版本

R2019a

标签

Community Treasure Hunt

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

Start Hunting!

Translated by