Access C++ Data Array Container Elements - MATLAB & Simulink (original) (raw)

Main Content

The C++ MATLABĀ® Data API CellArray and StructArray types are containers for other MATLAB Data Arrays. The elements in the containers are themselves arrays. There are two ways to access these elements:

Modify By Reference

To modify data in place, use a reference to the container element that you want to modify. For example, this code modifies the values of the first cell in theCellArray object. The first cell is a 1-by-3 logical array.

using namespace matlab::data;

ArrayFactory f;

auto cellArr = f.createCellArray({2,2}, f.createArray({1,3},{true, true, false}),
f.createCharArray("A char Array"), f.createScalar(-3374), f.createArray({1,3},{2.2, 3.3, -4.2}));

// Get a reference to the first cell of the cell array. TypedArrayRef ref = cellArr[0][0];

// Use the reference to modify the values in the cell. for (auto& e : ref) { e = false; }

After running this code, the first element of the cell array is a 1-by-3 logical array with each element set to false.

Copy Data from Container

You can access the data in a container using a shared copy. A shared copy enables you to get the data from the container or to modify the data in a copy that becomes nonshared when modified. Changing the data in a copy does not change the data in the container.

For example, this code creates a copy of the last cell in theCellArray, which is a 1-by-3 double array. The copy is modified by setting the first element in the double array to the numeric value5.5. After this modification, the value in theCellArray is unchanged and the copy is no longer a shared value.

using namespace matlab::data;

ArrayFactory f;

auto cellArr = f.createCellArray({2,2}, f.createArray({1,3},{true, true, false}), f.createCharArray("A cell Array"), f.createScalar(-3374), f.createArray({1,3},{2.2, 3.3, -4.2}));

// Get a shared copy of the last element of the cell array. TypedArray cpy = cellArr[1][1]; cpy[0] = 5.5;

See Also

Topics