Check the demo:
% nc filename to be written
file = 'myfile.nc' ;
delete(file) ;
%% Write lon and lat variables
% Get data
lon = 1:10 ;
lat = 1:10 ;
nx = length(lon) ;
nccreate(file,'lon','Dimensions',{'lon',1,nx},'DeflateLevel',7) ;
ncwrite(file,'lon',lon) ;
ny = length(lat) ;
nccreate(file,'lat','Dimensions',{'lat',1,ny},'DeflateLevel',7) ;
ncwrite(file,'lat',lat) ;
nccreate(file,'z','Dimensions',{'lon','lat'},'DeflateLevel',7) ;
data = rand(10) ;
ncwrite(file,'z',data,[1,1]) ;
%% Modify and write the variable
lon = ncread(file,'lon') ;
lat = ncread(file,'lat') ;
lon_km = deg2km(lon) ;
lat_km = deg2km(lat) ;
% Write variable
nccreate(file,'lon_kms','Dimensions',{'lon_kms',1,nx},'DeflateLevel',7) ;
ncwrite(file,'lon_kms',lon_km) ;
nccreate(file,'lat_kms','Dimensions',{'lat_kms',1,ny},'DeflateLevel',7) ;
ncwrite(file,'lat_kms',lat_km) ;