필터 지우기
필터 지우기

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 CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by