How would I loop this code to read each variable in my excel file so it can assign a grade for each number?

11 views (last 30 days)
The numbers on the file sheet:
69
97.1400
87.7400
93.6600
59
100
85.3600
62.8100
89.9300
100
91.3500
96.6700
76.7300
97.8600
66.4700
85.6000
87.1900
69.2100
98.8100
59.7600
83.1000
64.8800
74
99.7600
98.5700
97.3800
79
86.6500
98.8100
90.1200
89.6900
93.3300
91.6700
33
94.7600
56
85.4300
%the code%
x=readmatrix('MidtermExamGrades.xlsx');
if x<60
disp('your grade is F')
elseif x<70
disp('your grade is D')
elseif x<80
disp('your grade is C')
elseif x<90
disp('your grade is B')
else
disp('your grade is A')
end
  4 Comments
dpb
dpb on 19 Oct 2022
Well, what would your guess be?
What's the actual definition of the grade letter for the even scores?
HINT: Go look back at how was the question worded, precisely????
dpb
dpb on 19 Oct 2022
Then, of course, comes the Q? initially asked to evaluate over each grade input...
The if...elseif...end clauses are true IFF all elements of the logical expression are true and as always MATLAB evaluates the expression as the vector result so in reality, none of your cases are going to test True and be executed. (That's one of the pedagogical points being made in beginning MATLAB classes for such types of homework Q?)
So, one way is as you're thinking, write a loop and pass each element in turn -- that would work, but isn't "the MATLAB way" using the vector power of MATLAB as intended.
@David Hill showed you one way that solves both; I would have hoped we could have led you to find the solution on your own rather than handing out homework answers directly...use your own code with that as a hint as to how.
There's another "MATLAB-y" way that doesn't rely on the explicit if construct but would use a "lookup table" to return a letter grade given the score. It would operate over the whole vector without looping, too, as does the code below.
Are there restrictions on specific commands you were to use given?

Sign in to comment.

Accepted Answer

David Hill
David Hill on 19 Oct 2022
x=[69
97.1400
87.7400
93.6600
59
100
85.3600
62.8100
89.9300
100
91.3500
96.6700
76.7300
97.8600
66.4700
85.6000
87.1900
69.2100
98.8100
59.7600
83.1000
64.8800
74
99.7600
98.5700
97.3800
79
86.6500
98.8100
90.1200
89.6900
93.3300
91.6700
33
94.7600
56
85.4300];
y=zeros(size(x));
y(x<60)='F';
y(x>=60&x<70)='D';
y(x>=70&x<80)='C';
y(x>=80&x<90)='B';
y(x>=90)='A';
char(y)
ans = 37×1 char array
'D' 'A' 'B' 'A' 'F' 'A' 'B' 'D' 'B' 'A' 'A' 'A' 'C' 'A' 'D' 'B' 'B' 'D' 'A' 'F' 'B' 'D' 'C' 'A' 'A' 'A' 'C' 'B' 'A' 'A' 'B' 'A' 'A' 'F' 'A' 'F' 'B'

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!