How to read multi three dimensions netcdf files in a loop and append their third dimensions?

9 views (last 30 days)
Hello all,
Assume I have 4 NetCDF file, each file has 4 variable: precipitation (size: 3600x1800x248), time (size: 248x1), lon (size: 3600) and lat (size: 1800).
the size of each file is 21 x 23 x 248. I need to read all NetCDF files exist in my folder and append all their third dimensions of precipitation. The third dimension's pages (248) of the second file should come after the first file and so on.
I have written the below codes:
file = '198501.nc' ;
lat = ncread(file, 'lat') ;
lon = ncread(file, 'lon') ;
time = ncread(file, 'time') ;
% Here we extract our interest Lon and Lat (our study area)
lon = (lon(1951:1973)) ;
lat = (lat(410:430)) ;
pth = 'E:\DATA\Agro\MSWEP-data';
Files = dir(fullfile(pth, '*.nc'));
files = arrayfun(@(X) fullfile(pth, X.name), Files, 'uni', 0);
Info = ncinfo(files{1});
to append all third dimensions of all files together, a zero matrix with my_new_matrix size is initialized:
aaa = length(time) ; % which is 248
bbb = length(files) ; % which is 3
ccc = aaa * bbb ; % which is 744
my_new_matrix = zeros(length(lat), length(lon), ccc);
Now I would like to have a matrix with 21 x 23 x 744.
for ii = 1:length(files)
my_new_matrix(:,:,ii) = ncread(files{ii}, 'precipitation',[1951 410 1],[23 21 inf]);
end
here I can not produce my_new_matrix. I appreciate any help.

Accepted Answer

ANKUR KUMAR
ANKUR KUMAR on 28 Sep 2018
Edited: ANKUR KUMAR on 28 Sep 2018
Store it in fourth dimension "the size of each file in 21 x 23 x 248"
for ii = 1:length(files)
my_new_matrix(:,:,:,ii) = ncread(files{ii}, 'precipitation',[1951 410 1],[23 21 inf]);
end
After running the loop over 4 files, you will get a matrix of dimension 21 x 23 x 248 x 3. As a sample, I have taken a random matrix as A. Then use reshape command.
A=randi(10,21,23,248,3);
AA=reshape(A,21,23,[]);
size(AA)
ans =
21 23 744
  6 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!