Main Content

Pass Sparse Arrays to MATLAB From C++

MATLAB® sparse arrays provide efficient storage of double or logical data that has a large percentage of zeros. MATLAB sparse arrays support arithmetic, logical, and indexing operations. For more information, see Sparse Matrices.

Use matlab::data::ArrayFactory to create a matlab::data::SparseArray array. Write the data for the sparse array into buffers and use these buffers to create the sparse array. Pass the sparse array to MATLAB using MATLABEngine::setVariable.

#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"

void sparseArray() {

    using namespace matlab::engine;

    // Connect to named shared MATLAB session started as:
    // matlab -r "matlab.engine.shareEngine('myMatlabEngine')"
    String session(u"myMatlabEngine");
    std::unique_ptr<MATLABEngine> matlabPtr = connectMATLAB(session);

    // Define the data for the sparse array
    std::vector<double> data = { 3.5, 12.98, 21.76 };
    std::vector<size_t> rows = { 0,0,1 };
    std::vector<size_t> cols = { 0, 4, 8 };
    size_t nnz = 3;

    // Create buffers for the data
    matlab::data::ArrayFactory factory;
    buffer_ptr_t<double> data_p = factory.createBuffer<double>(nnz);
    buffer_ptr_t<size_t> rows_p = factory.createBuffer<size_t>(nnz);
    buffer_ptr_t<size_t> cols_p = factory.createBuffer<size_t>(nnz);

    // Write data into the buffers
    double* dataPtr = data_p.get();
    size_t* rowsPtr = rows_p.get();
    size_t* colsPtr = cols_p.get();
    std::for_each(data.begin(), data.end(), [&](const double& e) { *(dataPtr++) = e; });
    std::for_each(rows.begin(), rows.end(), [&](const size_t& e) { *(rowsPtr++) = e; });
    std::for_each(cols.begin(), cols.end(), [&](const size_t& e) { *(colsPtr++) = e; });

    // Use the buffers to create the sparse array
    matlab::data::SparseArray<double> arr =
        factory.createSparseArray<double>({ 2,9 }, nnz, 
            std::move(data_p), std::move(rows_p), std::move(cols_p));

    // Put the sparse array in the MATLAB workspace
    matlabPtr->setVariable(u"s", arr);

The MATLAB whos command shows that the array passed to the MATLAB workspace is a sparse array.

>> whos
  Name      Size            Bytes  Class     Attributes

  s         2x9               128  double    sparse 

For information on how to setup and build C++ engine programs, see Build C++ Engine Programs.

See Also

| |