Borrar filtros
Borrar filtros

Display name associated with max number in a while loop.

2 visualizaciones (últimos 30 días)
Lauren Harkness
Lauren Harkness el 16 de Oct. de 2017
Respondida: KL el 16 de Oct. de 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

Respuestas (1)

KL
KL el 16 de Oct. de 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)

Categorías

Más información sobre Environment and Settings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by