帮同学写的一个程序,目的是:把很多个NC数据合并在一起,并且每个.nc数据的变量名称是相同,我平常读.nc数据比较多,较少涉及写入。我先使用了IDL但是由于原数据的属性信息也很多,因此最后放弃。而MATLAB有基于现有的数据创建一个模板,对数据进行生成。
代码如下:
1.先对需要的.NC数据进行提取
2.提取所需的数据属性等
3.对数据进行赋值
tic
close all;
clear all;
sy=2005;
ey=2005;
for year=sy:ey
ncpath=strcat('J:\codeforYu\',num2str(year),'\');
files = dir([ncpath,'*.nc']);
len = length(files);
outfilepath='J:\codeforYu\new\';
filename=strcat('MERRA2_300.tavg1_2d_flx_Nx.',num2str(year),'.nc4.nc');%MERRA2_300.tavg1_2d_flx_Nx.2005_2005.nc4.nc
outtmp(576,361,len*4)=0.01; %len*4
time(len*4)=-1;
for i = 1:len
finfo = ncinfo([ncpath,files(i).name]) ; %'返回有关 NetCDF 数据源的信息'
% ncdisp([ncpath,files(i).name]) %'在命令行窗口中显示 NetCDF 数据源内容'
ncid = netcdf.open([ncpath,files(i).name],'nc_nowrite'); %'打开nc文件,获取文件id'
varid = netcdf.inqVarID(ncid,'RHOA'); % '获取所需变量的id号 varid'
p = netcdf.getVar(ncid, varid);
timetmp= ncread([ncpath,files(i).name],'time');
if i ==1
outtmp=p(:,:,0+1);
time=timetmp(0+1);
% time=cat(1,time,timetmp(6+1));
% time=cat(1,time,timetmp(12+1));
% time=cat(1,time,timetmp(18+1));
else
% 1440=24*60由于此时我们进行了合并,但是不同文件的时间起始是不同的
outtmp=cat(3,outtmp,p(:,:,0+1));
time=cat(1,time,timetmp(0+1)+(i-1)*1440);
end
outtmp=cat(3,outtmp,p(:,:,6+1));
outtmp=cat(3,outtmp,p(:,:,12+1));
outtmp=cat(3,outtmp,p(:,:,18+1));
time=cat(1,time,timetmp(6+1)+(i-1)*1440);
time=cat(1,time,timetmp(12+1)+(i-1)*1440);
time=cat(1,time,timetmp(18+1)+(i-1)*1440);
netcdf.close(ncid) %'关闭文件'
end
% lat的属性信息加载
myVarSchema = ncinfo([ncpath,files(1).name],'lat');
ncwriteschema(strcat(outfilepath,filename),myVarSchema);
% lon的信息加载
myVarSchema = ncinfo([ncpath,files(1).name],'lon');
ncwriteschema(strcat(outfilepath,filename),myVarSchema);
% 看一看咋样了
ncdisp(strcat(outfilepath,filename));
% RHOA属性信息加载
schema=ncinfo([ncpath,files(1).name],'RHOA');
% 修改一定的信息
schema.Dimensions(3).Length = len*4;%size(outtmp,3);%len*4
schema.Size=[576 361 len*4];%len*4
ncwriteschema(strcat(outfilepath,filename), schema);
% 看一看
% ncdisp(strcat(outfilepath,filename));
% time的属性信息加载
timeschema=ncinfo([ncpath,files(1).name],'time');
timeschema.Dimensions(1).Length = len*4;%size(outtmp,l3);%len*4
timeschema.Size=len*4;%len*4
ncwriteschema(strcat(outfilepath,filename), timeschema);
% 看一看
ncdisp(strcat(outfilepath,filename));
% 将本年第一个文件的lat给它
ncwrite(strcat(outfilepath,filename),'lat',361);
latData = ncread([ncpath,files(1).name],'lat');
ncwrite(strcat(outfilepath,filename),'lat',latData);
% 将lon给他
ncwrite(strcat(outfilepath,filename),'lon',576);
lonData = ncread([ncpath,files(1).name],'lon');
ncwrite(strcat(outfilepath,filename),'lon',lonData);
% RHOA的赋值
% outtmp=double(outtmp);
ncwrite(strcat(outfilepath,filename),'RHOA',outtmp);
% time的赋值
% time=int32(time);
ncwrite(strcat(outfilepath,filename),'time',time);
disp(['已经完成:' num2str(year) ]);
end
toc