问题
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);
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?
回答1:
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);
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'
回答2:
Try this:
for i=1:length(marks)
mark=marks(i);`
followed by your code and adding an end in the end for the for loop. You can also put the grades in a vector too and not just display them.
回答3:
Here is another solution slightly different from Luis Mendo 's answer:
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)
or you may use simple vectorized form
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';
I compared these methos with a benchmark that its result is:
-----------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.
The benchmark : Online Demo
来源:https://stackoverflow.com/questions/39819571/return-a-vector-of-grades-from-if-else-statements