フィルターのクリア

Display name associated with max number in a while loop.

2 ビュー (過去 30 日間)
Lauren Harkness
Lauren Harkness 2017 年 10 月 16 日
回答済み: KL 2017 年 10 月 16 日
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

回答 (1 件)

KL
KL 2017 年 10 月 16 日
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)

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by