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

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

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

Another option to do the same is to store in cell and use cat command.
A=randi(10,21,23,248);
for kk=1:3
AA{kk}=A; %in place of A, read the nc file variable which have the dimension 21 x 23 x248
end
AAA=cat(3,AA{:}));
size(AAA)
ans =
21 23 744
Dear Ankur, Thanks for your prompt reply. Actually at the moment the problem is here, I can not read all data with this:
for ii = 1:length(files)
my_new_matrix(:,:,ii) = ncread(files{ii}, 'precipitation',[1951 410 1],[23 21 inf]);
% I tried this one too
% My_new_matrix(:,:,:,ii) = ncread(files{ii}, 'precipitation',[1951 410 1],[23 21 inf]);
end
The error is: "Subscripted assignment dimension mismatch".
F=dir('*.nc')
for i =1:length(F)
i
pcp{i}=ncread(F(i).name,'precipitation',[1951 410 1],[23 21 inf]);
end
PCP=cat(3,pcp{:});
size(PCP)
Hope it helps.
Thanks for the answes!
How to save the resulting array as a netcdf-file?

Sign in to comment.

More Answers (0)

Asked:

on 28 Sep 2018

Edited:

on 1 Aug 2020

Community Treasure Hunt

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

Start Hunting!