Display name associated with max number in a while loop.

2 views (last 30 days)
I have the code below. It prints the maximum average score. The format of the given text file is each line 'names: scores' where scores are separated with commas. I want to print a statement with the name and average score of the person with the highest average score. How do I make sure the name printed corresponds with the high score and isn't just the last name on the list
function [wintrib] = hungerGames(txt)
fh = fopen(txt,'r');
filename = txt;
line = fgetl(fh);
maxa = -inf;
while ischar(line)
[names,scores]= strtok(line, ':');
scores = scores(2:end);
numArray=str2num(scores);
tot = sum(numArray);
avg = tot/(length(numArray));
line = fgetl(fh);
disp(names);
disp(avg);
maxa = max(maxa,avg);
maxa = round(maxa);
wintrib = sprintf('%s is most favored to win with a score of %d!',names,maxa);
end

Answers (1)

KL
KL on 16 Oct 2017
Import your data as table using readtable, it is so much easier. There's a perfect example for you.
T = readtable(fullfile(matlabroot,'examples','matlab','testScores.csv'),...
'ReadRowNames',true)
T.TestAvg = mean(T{:,2:end},2);
T(find(T.TestAvg==max(T.TestAvg)),end)

Categories

Find more on Elementary Math 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!