How to combine the data from multiple netcdf files and make it one .mat file?
29 views (last 30 days)
Show older comments
I have 100 years of rainfall data (100 netcdf file for each year) and one netcdf file contains one year rainfall data in months.
So the data format is like for one year netcdf file: lon*lat*12 %here time is 12 months
In the 100 years of netcdf file data, I need to get 1200 months data.
However, When I am using this loop to store the rainfall data, the loop didn't run for the entire 100 netcdf files. It just store the first netcdf file data.
I need to get the data like lon*lat*1200 (months)
%% List of files
list_of_files= dir(fullfile(ddir,'*.nc'))
%% Read Rainfall Data
for i=1:length(list_of_files);
filename = fullfile(ddir, list_of_files(i).name);
R = ncread(filename,'monthly_rain');
Rainfall (:,:,i) = R;
end
0 Comments
Accepted Answer
KSSV
on 22 Feb 2023
%% List of files
list_of_files= dir(fullfile(ddir,'*.nc'))
%% Read Rainfall Data
filename = fullfile(ddir, list_of_files(1).name);
% Read lon
lon = ncread(filename,'lon') ;
nx = length(lon) ;
% Read lat
lat = ncread(filename,'lat') ;
ny = length(lat) ;
%
nt = length(list_of_files) ;
Rainfall = [];
for i=1:nt
filename = fullfile(ddir, list_of_files(i).name);
R = ncread(filename,'monthly_rain');
Rainfall = cat(3,Rainfall,R) ;
end
More Answers (1)
Stephen23
on 22 Feb 2023
Edited: Stephen23
on 22 Feb 2023
Do not expand/concatenate the data inside the loop!
A more robust & efficient approach: concatenate once after the loop:
S = dir(fullfile(ddir,'*.nc'));
S = natsortfiles(S); % you might need this to get the correct file order
for k = 1:numel(S)
F = fullfile(ddir,S(k).name);
R = ncread(F,'monthly_rain');
S(k).data = R;
end
A = cat(3,S.data)
See Also
Categories
Find more on NetCDF in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!