MATLAB: How to write lat and lon as ‘data’ in a netcdf file (in addition to the other variable(s))

netcdfnetcdf fileswriting netcdf files

I have a question about writing out netcdf files:
My netcdf files are being written with a variable (with three dimensions), but there is no list of the lat or lon as separate variables, like I had in my input files which I used to create the output variable…
When I do an ncdump of the MyVar.nc file, I get the dimensions (time, lat, lon), the variable (MyVar (lat,lon,time), and the data, MyVar= (lots and lots of MyVar values), but no actual data for the lon, or lat associated with this variable (I searched for these using the less command, couldn't find them). So I am having trouble plotting the MyVar variable. My code is:
MyVar(:,:,:)=MyArray(:,:,:)
ncid=netcdf.create('myvar_model1.nc','NOCLOBBER');
dimid(1)=netcdf.defDim(ncid,'time',348);
dimid(2)=netcdf.defDim(ncid,'lon',144);
dimid(3)=netcdf.defDim(ncid,'lat',91);
varid=netcdf.defVar(ncid,'MyVar',NC_DOUBLE',dimid);
netcdf.endDef(ncid);
netcdf.putVar(ncid,varid,MyVar);
netcdf.close(ncid)
–do i have to add another varid? I tried this, it wouldn't allow me to specify the dimension I wanted to write as a variable… any further help would be appreciated. Thanks!

Best Answer

At a guess:
before the "endDef",
varid2 = netcdf.defVar(ncid, 'lat', NC_DOUBLE, dimid(2));
varid3 = netcdf.defVar(ncid, 'long', NC_DOUBLE, dimid(3));
Then after the putVar you have now, but before the close.
netcdf.putVar(ncid,varid2,lat);
netcdf.putVar(ncid,varid3,lon);