Recipe: Matlab program to read data from downloaded file
Back to G5NR Data Access Guide.
Problem
We want to read a downloaded data file using Matlab.
Solution
For the purpose of this example, we assume that we have already downloaded the file c1440_NR.inst01hr_3d_T_Cv.20060918_0900z.nc4
from the ftp server. For more information about file naming conventions, and how to download a file from the ftp server, please follow the links in the #See Also section.
The following code has been tested with Matlab version 2014a.
Code
This code reads the global temperature data from file and computes the maximum and minimum temperatures.
% NetCDF-4 file
opdfile = 'c1440_NR.inst01hr_3d_T_Cv.20060918_0900z.nc4';
% read global data
im = 720;
jm = 361;
lm = 72;
fprintf('Reading T (global)...');
T = ncread(opdfile, 'T');
fprintf('done.\n')
% compute max/min of T
fprintf('max(T): %f\n', max(T(:)));
fprintf('min(T): %f\n', min(T(:)));
Run
Running this Matlab script
>> run g5nr_reader.m
produces the output
Reading T (global)...done. max(T): 315.651245 min(T): 180.366745
Discussions
Modifications to read a subset of the data
The above Matlab script can be easily modified to read a subset of the temperature data instead. To read the temperature inside the box bounded by latitudes 25oN, 50oN and longitudes -130oW, -65oW, we need to modify the call to ncread
. We replace lines 4-10
of the above script with
% bounding box
% lons = -130:0.5:-65
% lats = 25:0.5:50
imin = round((-130. + 180.)/0.5);
imax = round(( -65. + 180.)/0.5);
jmin = round(( 25 + 90.)/0.5);
jmax = round(( 50 + 90.)/0.5);
% corresponding array sizes
im = imax-imin+1;
jm = jmax-jmin+1;
lm = 72; % read all 72 levels
% start/count for ncread
start = [imin, jmin, 1, 1];
count = [im, jm, lm, 1];
% now read
fprintf('Reading T (subset)...');
T = ncread(opdfile, 'T', start, count);
fprintf('done.\n')
The modified version of the code is g5nr_reader_subset.m.
Running this modified version
>> run g5nr_reader_subset.m
produces the output
Reading T (subset)...done. max(T): 305.604828 min(T): 191.695648
See Also
- File Spec: File:G5NR-Ganymed-7km FileSpec-ON6-V1.0.pdf
- Recipe: Retrieve (global) data from FTP server
- Recipe: Fortran program as OPeNDAP client