批量处理可以提高效率,这里提供一个可以批量读取nc文件的代码:
address = 'C:\Users\Hello World!!\DESKTOP\TerraClimate_ppt\';
% Get the list of files
udir = address;
form = '*.nc';
% Get the list of station names
files = GetFiles(udir,form);
[n,p] = size(files);
读取结果如下图,然后就可以批量循环读取即可。
下面给出一个代码:
address = 'C:\Users\Hello World!!\DESKTOP\TerraClimate_ppt\';
% Get the list of files
udir = address;
form = '*.nc';
% Get the list of station names
files = GetFiles(udir,form);
[n,p] = size(files);ncdisp(files(1,:));
file = files(1,:);
lon = ncread(file,'lon');
lat = ncread(file,'lat');
[lon,lat] = meshgrid(lon,lat);
sta = load('station.txt');for k = 1:n
time = ncread(files(k,:),'time');
dt2 = datetime((time)*24*3600, 'ConvertFrom', 'epochtime', 'Epoch', '1900-01-01');
[yy,mm,dd] = ymd(dt2);
for i = 1:12
tt(i) = time_transfer([yy(i),mm(i),dd(i)],1);
end
ppt = ncread(files(k,:),'ppt');
%% load station pos
for ii = 1:length(sta(:,1))
for jj = 1:12
tmax(k).rg(ii,jj) = interp2(lon,lat,ppt(:,:,jj)',sta(ii,1),sta(ii,2));
end
end
disp(k)
endtemp_min = cat(2,tmax.rg);
里面涉及的函数:
function files = GetFiles(udir,form)
% files = GetFiles(udir): Gets the list of files from the directory udir
% Generate the list of files that are needed.if ~isempty(udir)
% form = strcat(udir,form);
form = fullfile(udir,form);
end
% OK, See which files we have as form_files
d = dir(form);
% Get the names of all files in the directory
dname = {d.name};
% Get the list of file full names
files = []; % sites = [];
for i = 1:length(dname)
tname = cell2struct(dname(i),'name');
% sites = [sites;tname.name(4:7)];
% tname.name = strcat(udir,tname.name);
tname.name = fullfile(udir,tname.name);
files = [files;tname.name];
end
另一个处理时间的函数见:利用matlab处理netcdf文件中time变量的格式转换问题-CSDN博客
♥欢迎点赞收藏♥