MATLAB Answers

Read specific 2D matrix from 3D matrix variable from netCDF....

26 views (last 30 days)
KSSV
KSSV on 29 Dec 2015
Edited: Mohammad Abouali on 2 Jan 2016
Hi I have a netCDF file. I can access all its dimensions, variables etc in MATLAB using netCDF library. In the variables there is a variable whose size is mXnXp. Using the command:
data = netcdf.getVar(ncid,varid) ;
I can get the whole mXnXp variable, which is a 3D matrix. Here comes the problem, I dont want to access the whole variable, instead I want to access a 2D matrix mXn at a given number r = 1....p. Is there any command for this?
Thanking you all in advance

  0 Comments

Sign in to comment.

Accepted Answer

Mohammad Abouali
Mohammad Abouali on 29 Dec 2015
Edited: Mohammad Abouali on 29 Dec 2015
To read a matrix of mXn with third dimension being at r \in [1,p] do this:
data = netcdf.getVar(ncid,varid,[1,1,r],[m n 1]);
ALternatively you can use
data = ncread(netcdfFilename,varName,[1,1,r],[m n 1]);
I suggest the second method, i.e. using ncread, unless if you have some special reason to use the low-level netcdf API included in MATLAB. note that ncread does not require ncopen or ncid, or varid. It works just by their name.

  3 Comments

KSSV
KSSV on 30 Dec 2015
Dear Mohammad Abouali
Thanks a lot for the answer. I tried using both commands you mentioned. In the present case I have a variable of size 600X500X1441. I tried the following:
data = netcdf.getVar(ncid,varid,[1,1,r],[nx,ny,1]);
where nx = 600, ny = 500 and r = 1...1441. But it throwed the following error:
Error using netcdflib The NetCDF library encountered an error during execution of 'getVaraFloat' function - 'Start+count exceeds dimension bound (NC_EEDGE)'.
Error in netcdf.getVar (line 136) data = netcdflib(funcstr,ncid,varid,varargin{:});
I am trying to figure out what to do. Meanwhile, do you have any further suggestions?
Regards
KSSV
KSSV on 30 Dec 2015
Dear Mohammad Abouali
It worked with ncread and throws a error with netcdf.getVar. I will proceed with ncread as you suggested.
Regards
Mohammad Abouali
Mohammad Abouali on 2 Jan 2016
How did you get the dimensions of your NetCDF variable?
Here is the thing. MATLAB is the column order; while C is row major.
Therefore, if the metadata of the NetCDF says that your variable is of size 600X500X1441 (or if you used tools other than matlab), it is highly possible that when you read it in MATLAB it becomes: 1441X500X600. Completely reverse. So try the following command:
nx=600;
ny=500
data = ncread(netcdfFilename,varName,[r, 1, 1],[1, ny, nx]);
See if this one works

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by