How to process NC file in matlab

U
Usmanaleem · Jan 12, 2022 · 2.2K views
Question
I've monthly soil monisture NC file. This file contains monthly soil monisture data since 1948. I want to extract soil data within my shapefile in text file (Shapefile has also attached). I google alot to proccess NetCDF file in matlab find not solution, The ncdisp of my nc file is given below:     Format: netcdf4_classic Global Attributes: _NCProperties = 'version=1|netcdflibversion=4.4.1.1|hdf5libversion=1.10.1' Conventions = 'CF-1.0' title = 'CPC Soil Moisture' institution = 'NOAA/ESRL PSD' dataset_title = 'CPC Soil Moisture' history = 'Wed Oct 18 15:13:37 2017: ncks -d time,,-2 soilw.mon.mean.x.nc soilw.mon.mean.xx.nc Wed Oct 18 15:12:08 2017: ncks -d time,,-3 soilw.mon.mean.nc soilw.mon.mean.x.nc CPC Soil Moisture Obtained on Nov 2004 from CPC's website and written to netCDF by Cathy Smith 12/2004. he CPC Global monthly soil moisture dataset is a 1/2 degree resolution grid from 1948 to the present. The file is written in COARDS and CF compliant netCDF at NOAA ESRL/PSD https://www.esrl.noaa.gov/psd/ Converted to chunked, deflated non-packed NetCDF4 Jul 2014' NCO = '4.6.9' References = 'https://www.psl.noaa.gov/data/gridded/data.cpcsoil.html' Dimensions: lat = 360 lon = 720 time = 886 (UNLIMITED) Variables: lat Size: 360x1 Dimensions: lat Datatype: single Attributes: long_name = 'Latitude' units = 'degrees_north' actual_range = [8.98e+01 -8.98e+01] standard_name = 'latitude' axis = 'Y' coordinate_defines = 'point' lon Size: 720x1 Dimensions: lon Datatype: single Attributes: long_name = 'Longitude' units = 'degrees_east' actual_range = [2.50e-01 3.60e+02] standard_name = 'longitude' axis = 'X' coordinate_defines = 'point' soilw Size: 720x360x886 Dimensions: lon,lat,time Datatype: single Attributes: long_name = 'Model-Calculated Monthly Mean Soil Moisture' missing_value = -9.97e+36 units = 'mm' valid_range = [0.00e+00 1.00e+03] dataset = 'CPC Monthly Soil Moisture' var_desc = 'Soil Moisture' level_desc = 'Surface' statistic = 'Monthly Mean' parent_stat = 'Other' standard_name = 'lwe_thickness_of_soil_moisture_content' cell_methods = 'time: mean (monthly from values)' actual_range = [0.00e+00 1.00e+30] time Size: 886x1 Dimensions: time Datatype: double Attributes: long_name = 'Time' units = 'days since 1800-01-01 00:00:0.0' delta_t = '0000-01-00 00:00:00' avg_period = '0000-01-00 00:00:00' standard_name = 'time' axis = 'T' bounds = 'time_bnds' coordinate_defines = 'start' prev_avg_period = '0000-00-01 00:00:00' actual_range = [5.41e+04 8.10e+04]   I've tied file='data.nc'; ncdisp(file) long = ncread(file,'lon'); latt = ncread(file,'lat'); time = ncread(file,'time'); I want output of Soilw in this format in text file Date Soilw 01/01/2015 10 01/02/2015 20 01/03/2015 0.5 Please help me to convert monthly netcdf datainto text file using matlab please?
Expert Answer
Profile picture of Kshitij Singh
Kshitij Singh PhD Expert
Answered Sep 12, 2026

```html





How to Process .nc (NetCDF) Files in MATLAB


NetCDF (Network Common Data Form) is a multidimensional binary format used for climate, oceanographic, and geospatial data. MATLAB provides high-level functions (ncdisp, ncinfo, ncread, ncwrite) to inspect, read, slice, and plot this data.

1. Inspect Metadata and Structure


Always inspect the variables, dimensions, and attributes inside the file before loading data into memory.

filename = 'climate_data.nc';

% Print entire schema to the command window
ncdisp(filename);

% Store metadata programmatically in a struct
info = ncinfo(filename);

% List all variable names
varNames = {info.Variables.Name};
disp('Variables found in file:');
disp(varNames');

2. Read Data Variables and Attributes


Extract coordinates and measurement matrices using ncread() and attribute metadata with ncreadatt().

% Read coordinate grids
lon = ncread(filename, 'lon');
lat = ncread(filename, 'lat');
time = ncread(filename, 'time');

% Read main data matrix (e.g., Sea Surface Temperature)
sst = ncread(filename, 'sst');

% Read missing value attribute (_FillValue or missing_value)
fillVal = ncreadatt(filename, 'sst', '_FillValue');

% Replace fill values with NaN for accurate calculation and plotting
sst(sst == fillVal) = NaN;

3. Read a Subset (Hyperslab) for Large Files


When files are too large to fit in memory, specify start and count vectors to extract only the target time step or geographic bounding box.

% Syntax: ncread(filename, varName, start_indices, count_values, [stride])

% Example: Read all lon (360), all lat (180), but only the 1st time step
startIdx = [1, 1, 1];
countIdx = [Inf, Inf, 1]; % Inf reads the full length along that dimension

sst_timestep1 = ncread(filename, 'sst', startIdx, countIdx);

4. Plot 2D Spatial NetCDF Grids


Plot geographic coordinates using imagesc() or contourf().

figure('Color', 'w', 'Position', [100, 100, 750, 420]);

% Transpose matrix to match [lat, lon] grid indexing
imagesc(lon, lat, sst_timestep1');
set(gca, 'YDir', 'normal'); % Correct upside-down latitude orientation

colormap('jet');
cb = colorbar;
ylabel(cb, 'Temperature (K)');
xlabel('Longitude');
ylabel('Latitude');
title('NetCDF Spatial Grid: Sea Surface Temperature');
grid on;

5. Create and Write New NetCDF Files


To export computed results into a standard NetCDF file, define dimensions with nccreate() and write data with ncwrite().

outFile = 'output_results.nc';

% Define dimensions
nccreate(outFile, 'temperature', ...
    'Dimensions', {'lon', 360, 'lat', 180, 'time', 12}, ...
    'Datatype', 'single', ...
    'Format', 'netcdf4_classic');

% Write data into variable
dummyData = single(rand(360, 180, 12));
ncwrite(outFile, 'temperature', dummyData);

% Write metadata attributes
ncwriteatt(outFile, 'temperature', 'units', 'degrees_Celsius');
ncwriteatt(outFile, 'temperature', 'description', 'Simulated monthly mean temperature');

Core NetCDF Functions Summary














FunctionAction
ncdisp(file)Displays full file structure in command window.
ncinfo(file)Returns file metadata, variables, and attributes as a struct.
ncread(file, var)Loads variable data into a MATLAB array.
ncreadatt(file, var, att)Reads a specific metadata attribute (e.g. units).
nccreate(file, var, ...)Defines a new variable and its dimensions in an .nc file.
ncwrite(file, var, data)Writes MATLAB array data to a NetCDF variable.


Array Orientation: MATLAB reads NetCDF dimensions in Fortran order (column-major). A grid stored as (lon, lat) imports as [N_lon x N_lat]. Always transpose with data' when plotting with imagesc(lon, lat, data') or pcolor.




```

100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!