Loop daily average of hourly data

조회 수: 2 (최근 30일)
Fabian Moreno
Fabian Moreno 2020년 10월 7일
답변: Deepak 2024년 9월 9일
Hi there, I'm trying to make a loop to get daily average of temperatures from five stations in june. I have a cell of 5x1, each cell for each station, them I make an intersect to get each day of the month, june = 30 days.
for jj= 1 : length(Matrices)%stations(5)
for ii= 1 : length(M_24h)% days (30)
Matriz_24h{jj,1}(ii,8:9)=nanmean(Matrices{jj,1}(B1(ii,1):B1(ii+1,1),8:9));
end
I run the code, but at the end, it doens't get the average daily of the last day, I know that the time of the last day is until 23 hs, but I don't know how to get it.
result
day : 1, 2, 3, 4, 5, 6, 7, 8, ... 30
Average: 20.5 , 20.7, 21.2, 20.6, 21.8, 20.3, ..... NaN
Thanks

답변 (1개)

Deepak
Deepak 2024년 9월 9일
To my understanding, you have written a MATLAB code to get the daily average temperatures from five stations for the month of June. However, your code does not calculate the average for the last day and throws an “index out of bound” error.
Upon investigating the code, I found that the error occurs due to accessing the “B1(ii+1,1)” element (denoting the start of next day) when “ii” has reached 30, hence it throws “index out of bound error.
To fix this issue, for the last day of the month, we can use “end” notation to denote the end of data in the cell array, instead of accessing the start of next day in the following way:
Matriz_24h{jj}(ii, 8:9) =nanmean(Matrices{jj}(B1(ii):end, 8:9));
Below is the complete MATLAB code that addresses this task:
for jj = 1:length(Matrices)
numDays = length(M_24h);
for ii = 1:numDays
if ii < numDays
% For all days except the last one
Matriz_24h{jj,1}(ii,8:9) = nanmean(Matrices{jj,1}(B1(ii,1):B1(ii+1,1)-1, 8:9));
else
% For the last day, ensure you go to the end of the data
Matriz_24h{jj,1}(ii,8:9) = nanmean(Matrices{jj,1}(B1(ii,1):end, 8:9));
end
end
end
Please find attached the documentation of “array indexing” in MATLAB for reference:
I trust this will help to resolve the issue.

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by