How to define two dimension longitude, latitude and variable for saving data in netcdf format?

25 views (last 30 days)
Hello everyone,
I have longitude,laltitude and var data. All are in two dimension. All the provided examples in matlab community are focused on saving 1D latitude,longitude for 2d variable. I have tried below codes so far..
lon=rand(406,271); lat=rand(406,271); var=rand(406,271);
ncid = netcdf.create('Output.nc','NETCDF4');
dim_lon = netcdf.defDim(ncid,'lon',length(lon));
dim_lat = netcdf.defDim(ncid,'lat',length(lat));
var1_lon = netcdf.defVar(ncid,'lon','double',dim_lon);
var1_lat = netcdf.defVar(ncid,'lat','double',dim_lat);
var_50 = netcdf.defVar(ncid,'var','float', [dim_lat dim_lon]);
netcdf.putAtt(ncid,var1_lon,lon);
netcdf.putAtt(ncid,var1_lat,lat);
netcdf.putAtt(ncid,var_50,var);
I think the above code is suitable for 1D lat-lon dimension saving in netcdf. I find it difficult (showing error) to use it for 2D lat-lon data.
Looking forward to any sort of help or directions. Thanks in advance.

Accepted Answer

CHIRANJIT DAS
CHIRANJIT DAS on 24 Jun 2022
dimidlon = netcdf.defDim(ncid,'lon',size(lon,1));
dimidlat = netcdf.defDim(ncid,'lat',size(lon,2));
%variables
tim_ID=netcdf.defVar(ncid,'time','double',dimidtim);
lon_ID=netcdf.defVar(ncid,'lon','double',[dimidlon,dimidlat]);
lat_ID=netcdf.defVar(ncid,'lat','double',[dimidlon dimidlat]);
Try it, this should probably work in your problem scenario.
Good luck

More Answers (1)

KSSV
KSSV on 23 Jun 2022
lon=rand(406,271); lat=rand(406,271); var=rand(406,271);
[nx,ny] = size(lon) ;
% nc filename to be written
file = 'myfile.nc' ;
nccreate(file,'x','Dimensions',{'x',1,nx},'DeflateLevel',7) ;
nccreate(file,'y','Dimensions',{'y',1,ny},'DeflateLevel',7) ;
nccreate(file,'lon','Dimensions',{'x','y'},'DeflateLevel',7) ;
ncwrite(file,'lon',lon) ;
nccreate(file,'lat','Dimensions',{'x','y'},'DeflateLevel',7) ;
ncwrite(file,'lat',lat) ;
nccreate(file,'var','Dimensions',{'x','y'},'DeflateLevel',7) ;
ncwrite(file,'var',var) ;
  6 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!