Add array to NetCDF file as variable
4 views (last 30 days)
Show older comments
I have a NetCDF file and I'm trying to convert some of the variables into different units. So I extracted the relevant variable (NH4 concentration) and used arrayfun to convert every element in the array to the desired units.
ammdata = ncread('out1.nc','NH4'); % comes out as a 4-D single (lat, long, depth, time)
ammdata2 = arrayfun(@molar,ammdata); % also a 4-D single
function y = molar(x)
y = x/(14.0067/18.039)*(1/10^3)/(18.039/10^3);
end
Now I need to add the new variable (ammdata2) back to the original NetCDF file as a new variable. I can find documentation online for how to create a new variable, but not how to populate it with an existing multidimentional array.
I currently have the R2021a prerelease installed, not sure if that's relevant.
0 Comments
Answers (1)
KSSV
on 29 Jan 2021
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) ;
0 Comments
See Also
Categories
Find more on NetCDF in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!