Work with mxArrays - MATLAB & Simulink (original) (raw)
Main Content
The MAT-File Interface Library lets you access MATLABĀ® arrays (type mxArray
) in a MAT-file. To work directly with an mxArray
in a C/C++ application, use functions in the Matrix Library.
You can find examples for working with the mxArray
type in the matlabroot
/extern/examples/mex
and matlabroot
/extern/examples/mx
folders. The following topics show C code examples, based on these MEX examples, for working with cells and structures. The examples show how to read cell and structure arrays and display information based on the type of the mxArray
within each array element.
If you create an application from one of the MEX examples, here are some tips for adapting the code to a standalone application.
- The MAT-file example,
matdgns.c
, shows how to open and read a MAT-file. For more information about the example, see Read MAT-File in C/C++. - The MEX example,
explore.c
, has functions to read any MATLAB type using the mxClassID function. For more information about the example, see Using Data Types. - Some MEX examples use functions, such as
mexPrintf
, from theC MEX API library,libmex
. You do not need to use these functions to work with anmxArray
, but if your program calls any of them, you must link to the MEX Library. To do this, addlibmex.lib
to the link statement.
Read Structures from a MAT-File
The matreadstructarray.c
example is based on the analyze_structure
function in explore.c
. For simplicity, this example only processes real elements of type double
; refer to the explore.c
example for error checking and processing other types.
To see the code, open the file in the MATLAB Editor.
After building the program, run the application on the MAT-file, testpatient.mat
.
First, create a structure patient
and save it.
patient(1).name = 'John Doe'; patient(1).billing = 127.00; patient(1).test = [79 75 73; 180 178 177.5; 172 170 169]; patient(2).name = 'Ann Lane'; patient(2).billing = 28.50; patient(2).test = [68 70 68; 118 118 119; 172 170 169];
save testpatient.mat
Calculate the total of the billing
field.
!matreadstruct testpatient.mat patient billing
Total for billing: 155.50
Read Cell Arrays from a MAT-File
The matreadcellarray.c
example is based on the analyze_cell
function in explore.c
.
To see the code, open the file in the MATLAB Editor.
After building the program, run the application on the MAT-file, testcells.mat
.
First, create three cell variables and save.
cellvar = {'hello'; [2 3 4 6 8 9]; [2; 4; 5]}; structvar = {'cell with a structure'; patient; [2; 4; 5]}; multicellvar = {'cell with a cell'; cellvar; patient};
save testcells.mat cellvar structvar multicellvar
Display the mxArray
type for the contents of cellcellvar
.
!matreadcell testcells.mat cellvar
0: string 1: numeric class 2: numeric class