Hi, so I am writing a piece of code to loop to find the max in a data set. I need to find the max for every year in a 30 year period. (all the data is in an excel spreadsheet)
My program half works, but the problem I have is the way the data is arranged in the spreadsheet a year, for example, 1987 is in there multiple times since the datasheet has values for every minute. My loop loops through every minute to find the average, which works fine, but when I increment it up, it repeats the same year. How could I have it skip the same year? I attach my code and a screenshot of the data table for reference.
for i=1:777013
currentYear = years(i);
for j=1:777013
if(years(j) == currentYear)
if(height(j) > currentMax)
currentMax = height(j);
end
else
disp('The height total for')
disp(currentYear)
disp('was')
disp(currentMax)
break
end
end
end

댓글 수: 1

Mehmed Saad
Mehmed Saad 2020년 4월 20일
편집: Mehmed Saad 2020년 4월 20일
there are much easier way to solve this problem instead of using nested for loops
Try Logical Indexing

댓글을 달려면 로그인하십시오.

 채택된 답변

KSSV
KSSV 2020년 4월 20일
편집: KSSV 2020년 4월 20일

0 개 추천

Let Y be your year data.
[c,ia,ib] = unique(Y) ;
N = length(c) ;
iwant = zeros(N,1) ;
for i = 1:N
iwant(i) = mean(height(ib==i)) ;
end

댓글 수: 2

Hi thank you so much this worked! however I have one more question/issue. I am trying to "reset the max value" after the second loop is done so it can properly calculate the new max value. However it won't reset properly, do you have any suggestions?
previousYear = 3;
currentMax = 0;
years1 = unique(years)
for i=1:29
currentYear = years1(i);
for j=1:777013
if(years(j) == currentYear)
if(height(j) > currentMax)
currentMax = height(j);
end
else
disp('The height total for')
disp(currentYear)
disp('was')
disp(currentMax)
currentMax = 0
break
end
end
end
KSSV
KSSV 2020년 4월 21일
It is not clear to me what you are trying to do.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2020년 4월 20일

댓글:

2020년 4월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by