COnvert .txt file to NetCDF

16 次查看(过去 30 天)
Chiara Lanzi
Chiara Lanzi 2021-10-29
回答: Gyan Vaibhav 2023-10-13
Hi everyone,
I want to conevrt a txt file to NetCDF file. I have 3 columns and 31332 rows. The first two columns are x and y coordinates and the last columns are the data related to the points. I read the documentation for nccreate and ncwrite to start with and this is what I achieved so far:
%create a nc file with a variable called Var1
nccreate('myexample.nc','x','Dimension',{'r',31332})
nccreate('myexample.nc' ,'lat','Dimension',{'c',31332})
nccreate('myexample.nc' ,'z','Dimension',{'c',31332})
ncdisp('myexample.nc')
ncwrite('myexample.nc','z',res(31332))
But it is not working. I think, I don't understand very well how to set up the variable at the beginning and that is my mistake. Does anyone know about this??
Thanks for help,
Chiara

回答(1 个)

Gyan Vaibhav
Gyan Vaibhav 2023-10-13
Hi Chiara,
To convert a text file to a NetCDF file, you need to properly define the dimensions and variables in the NetCDF file. Based on your description, it seems like you have three columns: x, y coordinates, and data values, with 31332 rows.
Before you can write a variable to a netcdf file, you need to first set up the NetCDF file with the proper variable names, dimensions, etc. via "nccreate".
Here's how you can modify your code to create the NetCDF file and write the data:
% Create a NetCDF file
nccreate('myexample.nc', 'x', 'Dimensions', {'r', 31332});
nccreate('myexample.nc', 'y', 'Dimensions', {'r', 31332});
nccreate('myexample.nc', 'data', 'Dimensions', {'r', 31332});
% Write the data to the NetCDF file
x = % read x coordinates from your text file
y = % read y coordinates from your text file
data = % read data values from your text file
ncwrite('myexample.nc', 'x', x);
ncwrite('myexample.nc', 'y', y);
ncwrite('myexample.nc', 'data', data);
% Display the NetCDF file structure
ncdisp('myexample.nc');
By following this approach, you should be able to create a NetCDF file with the desired dimensions and variables and write the data into it.
Hope this helps!

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by