Linear indexing for multi-dimensional struct array in C++ API

In plain MATLAB I can use the following code and ignore the actual dimensions:
s = repmat(struct('exampleField',1),[2,3,4,5]);
for ii = 1:numel(s)
disp(s(ii).exampleField)
end
However, in the C++ API, I can't use the linear indexing as the following code fails with the error: "Not enough indices provided."
void func(matlab::data::StructArray s){
for (size_t ii = 0; ii < s.getNumberOfElements(); ++ii)
std::cout << s[ii][std::string("exampleField")] << std::endl;
}
Is there a way to still use linear indexing? Without linear indexing generic code development gets nearly impossible.

 Accepted Answer

Linear indexing can be achieved using the 'matlab::data::TypedIterator<T>'. This is a templated C++ class which provides random access iterator in memory order and can be used to iterate and print the struct array. Further details about this class can be found in the link below. 
The following code describes two ways to assign and display the values in a struct array.
#include "MatlabDataArray.hpp"
#include "mex.hpp"
#include "mexAdapter.hpp"
using namespace matlab::data;
using matlab::mex::ArgumentList;
class MexFunction : public matlab::mex::Function {
public:
void operator()(ArgumentList outputs, ArgumentList inputs)
{
ArrayFactory factory;
StructArray S = factory.createStructArray({2, 3, 4, 5 }, { "exampleField" });
// Assign and display using Iterator
TypedIterator<Struct> it(S.begin());
for (size_t i=0; i<S.getNumberOfElements(); i++)
{
// Assign values to exampleField
it[i]["exampleField"] = factory.createArray<int>({1, 1}, {(int)i});
// Display value
std::cout << "S[" << i << "] = " << (int)(it[i]["exampleField"])[0] << std::endl;
}
// Another way to assign and display values
int cnt = 0;
for (auto& elem : S) {
elem["exampleField"] = factory.createArray<int>({1, 1}, {2*cnt});
cnt = cnt + 1;
std::cout << "S[" << cnt << "] = " << (int)(elem["exampleField"])[0] << std::endl;
}
}
};
 

More Answers (0)

Products

Release

R2021a

Community Treasure Hunt

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

Start Hunting!