mex cplusplus matlab::data::RowMajorIterator
Show older comments
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?
Answers (1)
Madheswaran
on 26 Mar 2025
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:
- https://mathworks.com/help/matlab/apiref/matlab.data.rowmajor.html
- https://mathworks.com/help/matlab/ref/mex.html
Hope this helps!
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!