Program not printing to a text file properly

4 views (last 30 days)
read = importdata("testscores.txt");
StudentID = read(:,1);
Score = read(:,2);
fid = fopen('FinalGrades.txt', 'w');
FinalGrades = read(:,2);
LowScore = min(FinalGrades);
HighScore = max(FinalGrades);
AverageScore = mean(FinalGrades);
StandardDeviation = std(FinalGrades);
TotalA = 0;
TotalB = 0;
TotalC = 0;
TotalD = 0;
TotalF = 0;
fprintf("Here is a summary of all the scores \n")
fprintf("The lowest score in the class was a %0.1f. \n", LowScore)
fprintf("The highest score in the class was a %0.1f\n", HighScore)
fprintf("The average score of the entire class was %0.1f \n", AverageScore)
fprintf("The standard deviation of all the scores was %0.3f \n", StandardDeviation)
StudentID = read(1);
Score = read(2);
Grades = cell(size(Score));
for i = 1:numel(Score);
if Score(i) >= AverageScore + 1.5 * StandardDeviation
Grades{i} = 'A';
elseif Score(i) >= AverageScore + 0.5 * StandardDeviation
Grades{i} = 'B';
elseif Score(i) >= AverageScore - 0.5 * StandardDeviation
Grades{i} = 'C';
elseif Score(i) >= AverageScore - 1.5 * StandardDeviation
Grades{i} = 'D';
else
Grades{i} = 'F';
end
end
fid=fopen("FinalGrades.txt", "w");
for i = 1:numel(StudentID);
fprintf(fid, '%d\t%s\n', StudentID(i), Grades{i});
end
I have this code, which is supposed to read a bunch of data from a .txt file, then determine which student by student ID got what letter grade. It seems to work fine up until the point where I need it to print the table of Student IDs and letter grades to a new text file. When that occurs, it only prints one line of 1 student ID and 1 letter grade. Not sure what is going wrong.

Accepted Answer

Voss
Voss on 25 Feb 2024
At first you make StudentID and Score column vectors
StudentID = read(:,1);
Score = read(:,2);
and later you overwrite those to be scalars
StudentID = read(1);
Score = read(2);
That's why it's only outputting a single ID and grade. Remove the second definition and stick with the first.
Also, you're opening the file with fopen two times. Just open it once, and don't forget to fclose it when you're done.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!