从if-else语句返回Grades的向量 [英] Return a vector of Grades from if-else statements

查看:143
本文介绍了从if-else语句返回Grades的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个if-else如果这个结构赋予我A,B,C,D,F的等级,取决于0-100的分数。

I have an if-else if construct which gives me grades A, B, C, D, F depending on marks from 0-100.

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) '分数'。我不确定;如何通过这一行代码输入每个数字标记来实现输出向量的等级?

Now, I have a another long vector of numeric marks (from 0-100) of size Ax1 called 'marks'. I am not sure; how to input each of those numeric marks through this line of code to achieve an output vector of grades?

推荐答案

您可以通过矢量化的方式来完成这些工作:

You can do it in a vectorized way, along these lines:

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);

在这个例子中,这给出了char向量od等级

In the example, this gives the char vector od grades

grades =
BBFAAD






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


If you prefer cell array output, change the first line to

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

可以给

which will give

grades =
    'B'    'B'    'F'    'A'    'A'    'D'

这篇关于从if-else语句返回Grades的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆