Main Content

Access C++ Data Array Container Elements

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:

  • Get a reference to the elements of the container.

  • Get a shared copy of the elements of the container.

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 the CellArray 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<bool>({1,3},{true, true, false}),                                           
    f.createCharArray("A char Array"),
    f.createScalar<int32_t>(-3374),
    f.createArray<double>({1,3},{2.2, 3.3, -4.2}));

// Get a reference to the first cell of the cell array.
TypedArrayRef<bool> 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 the CellArray, which is a 1-by-3 double array. The copy is modified by setting the first element in the double array to the numeric value 5.5. After this modification, the value in the CellArray 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<bool>({1,3},{true, true, false}),
    f.createCharArray("A cell Array"),
    f.createScalar<int32_t>(-3374),
    f.createArray<double>({1,3},{2.2, 3.3, -4.2}));

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

Related Topics