MATLAB Answers

Creating a Histogram of Letter grades converted from number grades

38 views (last 30 days)
Christian Agostino
Christian Agostino on 23 Feb 2021
Answered: dpb on 24 Feb 2021
I am trying to reassign the values in a number array to letters to appear in a histogram. Attached is the code I wrote. Every time I run it, an error reading
"Unable to perform assignment because the left and right sides have a different number of elements.
Error in Problem_1_392 (line 15)
Grades(i)=num2str('C-');"
Can anyone help?
Grades=xlsread("hwk1prob1.xlsx");
i=1;
while i<=numel(Grades)
if Grades(i)<60
Grades(i)=num2str('F');
elseif Grades(i)<=69.9
Grades(i)=num2str('D');
elseif Grades(i)<=73.9
Grades(i)=num2str('C-');
elseif Grades(i)<=76.9
Grades(i)=num2str('C');
elseif Grades(i)<=79.9
Grades(i)=num2str('C+');
elseif Grades(i)<=83.9
Grades(i)=num2str('B-');
elseif Grades(i)<=86.9
Grades(i)=num2str('B');
elseif Grades(i)<=89.9
Grades(i)=num2str('B+');
elseif Grades(i)<=94.9
Grades(i)=num2str('A-');
elseif Grades(i)>=95.9
Grades(i)=num2str('A');
end
i=i+1;
end
histogram(Grades,10);
xlabel('Letter Grade')
ylabel('Number of Students')
title('Frequency of ME 392 Grades 2003-2016')

Answers (2)

the cyclist
the cyclist on 23 Feb 2021
I'm sorry to say that the approach in your code is so misguided, that it is probably not worth debugging it. You need a different overall approach.
I would think the best one would be to do the histogram on the numeric grades themselves (using the grade cutoffs as the bin edges), and then changing the labels on the resulting histogram to indicate the letter grades.

dpb
dpb on 24 Feb 2021
One way that illustrates lookup table approach...
GRADES=[0,60,69.9,73.9,76.9,79.9,83.9,86.9,89.9,94.9,95.9,100]; % letter grade numeric breakpoints
LETTERS={'F','F','D','C-','C','C+','B-','B','B+','A-','A','A'}; % associated letter grade
Example usage
>> grades=min(round(randi([50,100],20,1)+rand(20,1),1),100); % some random possible grades
>> LETTERS(interp1(GRADES,1:numel(GRADES),grades,'next')) % lookup LETTER from GRADES by grades
ans =
1×20 cell array
{'D'} {'A-'} {'A-'} {'C+'} {'F'} {'C'} {'B+'} {'C-'} {'C+'} {'F'} {'B-'} {'C+'} {'A'} {'A'} {'F'} {'A-'} {'D'} {'F'} {'A-'} {'C+'}
>> [num2cell(grades.');ans] % compare is what wanted...
ans =
2×20 cell array
Columns 1 through 13
{[68.2000]} {[92.1000]} {[94.6000]} {[79.9000]} {[50.4000]} {[75.3000]} {[87.9000]} {[71.9000]} {[77.7000]} {[51.7000]} {[82.9000]} {[79.3000]} {[95.9000]}
{'D' } {'A-' } {'A-' } {'C+' } {'F' } {'C' } {'B+' } {'C-' } {'C+' } {'F' } {'B-' } {'C+' } {'A' }
Columns 14 through 20
{[96.1000]} {[50.7000]} {[93.2000]} {[62.8000]} {[56.7000]} {[90.6000]} {[78]}
{'A' } {'F' } {'A-' } {'D' } {'F' } {'A-' } {'C+'}
>>

Community Treasure Hunt

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

Start Hunting!