mex cplusplus matlab::da​ta::RowMaj​orIterator

This is an example of iterating through a matrix in Matlab's default column-major setup
void operator()(matlab::mex::ArgumentList outputs, matlab::mex::ArgumentList inputs)
{
const matlab::data::TypedArray<double> data = std::move(inputs[0]);
for (auto it = data.begin(); it != data.end();)
{
std::cout << *it++ << " ";
}
}
How can I do the same to iterate row-major with a matlab::data::RowMajorIterator iterator?

回答(1 个)

You can use the row-major iterator by utilizing the RowMajor class as follows:
void operator()(matlab::mex::ArgumentList outputs, matlab::mex::ArgumentList inputs)
{
const matlab::data::TypedArray<double> data = std::move(inputs[0]);
// Option 1: Using explicit iterators
for (auto it = matlab::data::RowMajor::begin<double>(data);
it != matlab::data::RowMajor::end<double>(data);)
{
std::cout << *it++ << " ";
}
// Option 2: Using range-based for loop with writableElements
auto range = matlab::data::RowMajor::writableElements<double>(data);
for (const auto& elem : range) {
// ... Your code ...
}
}
Make sure to include "RowMajorIterator.hpp" in your header files, and add the appropriate include path when compiling:
mex yourfile.cpp -I"matlabroot/extern/include/MatlabDataArray"
replace 'matlabroot' with abosolute path of your 'matlabroot' in the above command.
For more information, refer to the following documentations:
  1. https://mathworks.com/help/matlab/apiref/matlab.data.rowmajor.html
  2. https://mathworks.com/help/matlab/ref/mex.html
Hope this helps!

类别

帮助中心File Exchange 中查找有关 Write C Functions Callable from MATLAB (MEX Files) 的更多信息

产品

版本

R2024b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by