Display name associated with max number in a while loop.

2 Ansichten (letzte 30 Tage)
Lauren Harkness
Lauren Harkness am 16 Okt. 2017
Beantwortet: KL am 16 Okt. 2017
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

Antworten (1)

KL
KL am 16 Okt. 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)

Kategorien

Mehr zu Elementary Math finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by