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.

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

See Also

Topics