How to combine the data from multiple netcdf files and make it one .mat file?

27 ビュー (過去 30 日間)
Pankaj R. Kaushik
Pankaj R. Kaushik 2023 年 2 月 22 日
編集済み: Stephen23 2023 年 2 月 22 日
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

採用された回答

KSSV
KSSV 2023 年 2 月 22 日
%% 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

その他の回答 (1 件)

Stephen23
Stephen23 2023 年 2 月 22 日
編集済み: Stephen23 2023 年 2 月 22 日
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)

カテゴリ

Help Center および File ExchangeNetCDF についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by