MATLAB: Read specific 2D matrix from 3D matrix variable from netCDF….

2d matrix3d matrixncidnetcdfnetcdf.getvarread

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

Best Answer

  • 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.