how to calculate 3D netcdf in matlab?

2 views (last 30 days)
Habtamu Tsegaye
Habtamu Tsegaye on 3 Feb 2023
Answered: Ronit on 25 Sep 2024
I have 300-by-240-by-365 3D netcdf file for 16 years rainfall data. I need to have mean monthly data which contains 300-by-240-by-12. how can I do this?
here is my trial script
clear all;
MP2(1:300,1:240,1:12)=0; % in case of IMERG lat is arranged in row where as lon is arranged in column((lat:lon,year)=0) is Monthly Precipitation (MP) with zero intial matrix to start for loop
for yy=2002:2017 % the year from 2002 to 2017
for mm=1:12
ap2(1:300,1:240)=0;
E = eomday(yy,mm);
dy=YYYYMMDD2doy(yy,mm,1);
hits1 = ['D:\Rainfall_Data_from_Satelite\CHIRPS/','chirps-v2.0.',num2str(yy,'%02d'),'.days_p05.nc'];
fe = dir(hits1);
ncid = netcdf.open(hits1);
lat=netcdf.getVar(ncid,0,'single'); % latitude
lon=netcdf.getVar(ncid,1,'single'); % longitude
p1=ncread(hits1,'precip',[4269,1061,dy],[300,240,E]);% days in a month
p1_sum=nansum(p1,3); % a monthly rainfall using sum of daily data
% scale=netcdf.getAtt(ncid,3,'scale_factor');
% offset=netcdf.getAtt(ncid,3,'add_offset');
netcdf.close(ncid);
end
MP2(:,:,mm)=p1_sum;
end

Answers (1)

Ronit
Ronit on 25 Sep 2024
Hello Habtamu,
To calculate the mean monthly rainfall data from your "3D NetCDF file", you need to ensure that you are correctly iterating through the years and months, and accumulating the monthly precipitation data.
clear all;
meanMonthlyPrecipitation = zeros(300, 240, 12);
for mm = 1:12
% Initialize a temporary matrix to accumulate monthly precipitation
tempMonthlySum = zeros(300, 240);
yearCount = 0;
for yy = 2002:2017
E = eomday(yy, mm);
dy = YYYYMMDD2doy(yy, mm, 1);
% Construct the file path and add here
if exist(hits1, 'file')
ncid = netcdf.open(hits1);
% Read the precipitation data for the current month
p1 = ncread(hits1, 'precip', [4269, 1061, dy], [300, 240, E]);
% Replace NaN values with zeros for summing
p1(isnan(p1)) = 0;
% Sum the daily precipitation data to get monthly totals
p1_sum = sum(p1, 3);
% Accumulate the monthly totals
tempMonthlySum = tempMonthlySum + p1_sum;
yearCount = yearCount + 1;
netcdf.close(ncid);
end
end
% Calculate the mean monthly precipitation by dividing by the number of years
if yearCount > 0
meanMonthlyPrecipitation(:, :, mm) = tempMonthlySum / yearCount;
end
end
% Now, meanMonthlyPrecipitation contains the mean monthly data over 16 years
Make sure that the "YYYYMMDD2doy" function is correctly defined and available in your environment.
Hope it helps!

Tags

Community Treasure Hunt

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

Start Hunting!