COnvert .txt file to NetCDF
19 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Gyan Vaibhav
on 13 Oct 2023
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!
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!