从if-else语句返回Grades向量

时间:2016-10-02 17:16:54

标签: matlab function if-statement for-loop

我有一个if-else if构造,根据0-100的标记给我A,B,C,D,F等级。

if (mark > 100) | (mark < 0)
disp('Invalid mark');
return; % Exit from the program.
end % Of first if statement
if mark >= 80 % Mark is in range 80 - 100.
grade = 'A';
elseif mark >= 70 % Mark is in range 70 - 79.
grade = 'B'; 
elseif mark >= 60 % Mark is in range 60 - 69.
grade = 'C';
elseif mark >= 50 % Mark is in range 50 - 59.
grade = 'D'  
else % Mark is in range 0 - 44.
grade = 'F';
end
disp(grade);

现在,我有另一个长度为Ax1的数字标记向量(从0到100),称为&#39;标记&#39;。我不确定;如何通过这行代码输入每个数字标记,以实现成绩的输出向量?

3 个答案:

答案 0 :(得分:1)

您可以按照矢量化方式执行此操作:

save('your_filename.mat', 'database')

在该示例中,这给出了char矢量od等级

grade_names = 'FDCBA';
th = [50 60 70 80]; % thresholds that define the grades
marks = [75 70 33 99 88 58]; % data
grades_num = 1 + sum(bsxfun(@ge, marks(:).', th(:) ), 1); % vector with numbers
    %  indicating grade: 1 for the first ('F'), 2 for the second ('D') etc
grades = grade_names(grades_num);

如果您更喜欢单元格数组输出,请将第一行更改为

grades =
BBFAAD

将给出

grade_names = {'F' 'D' 'C' 'B' 'A'};

答案 1 :(得分:0)

试试这个:

for i=1:length(marks) =标志标记(I);`

后面跟着你的代码 并为for循环添加一个结尾。 您也可以将等级放在矢量中,而不仅仅是显示它们。

答案 2 :(得分:0)

这是另一个与Luis Mendo的答案略有不同的解决方案:

if numel(find((mark > 100) | (mark < 0))) > 0
    disp('Invalid mark');
    return; % Exit from the program.
end % Of first if statement
%array of break points
brkpnt = [0 50:10:80 101];
%distance between breakpoints
cnt = diff(brkpnt);
%table of grades corresponding to related marks
Grades = repelem('FDCBA', cnt);
%the result. 1  added to mark to make indices greater than 0
grade = Grades(mark + 1)

或者您可以使用简单的矢量化形式

grade(mark >= 80) = 'A';
grade(mark < 80 & mark >= 70) = 'B';
grade(mark < 70 & mark >= 60) = 'C';
grade(mark < 60 & mark >= 50) = 'D';
grade(mark < 50) = 'F';

我将这些方法与结果的基准比较:

-----------repelem method---
Elapsed time is 0.00621986 seconds.
-----------bsxfun method---
Elapsed time is 0.022429 seconds.
-----------simple vectorized method---
Elapsed time is 0.0253041 seconds.
-----------for loop method---
Elapsed time is 7.7302 seconds.

基准:Online Demo