Can you modify this mex file to accept an array of MATLAB objects?

6 views (last 30 days)
Hello all,
This page https://www.mathworks.com/help/matlab/matlab_external/use-matlab-objects-in-mex-functions.html expalins how to pass an object from MATLAB to a C++ mex function. The MATLAB object is a simple EmployeeID as follows:
classdef EmployeeID
properties
Name (1,:) char
Picture (1000,800) uint8
end
methods
function obj = EmployeeID(n,p)
if nargin > 0
obj.Name = n;
obj.Picture = p;
end
end
end
end
The mex code is as follows:
#include "mex.hpp"
#include "mexAdapter.hpp"
using matlab::mex::ArgumentList;
using namespace matlab::data;
class MexFunction : public matlab::mex::Function {
std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine();
public:
void operator()(ArgumentList outputs, ArgumentList inputs) {
// Move object to variable
Array obj = std::move(inputs[0]);
// Get property value and modify
TypedArray<uint8_t> imageData = matlabPtr->getProperty(obj, u"Picture");
for (auto& elem : imageData) {
if (elem > 240) {
elem = elem - elem/100;
}
}
// Set property value and assign to output
matlabPtr->setProperty(obj, u"Picture", imageData);
outputs[0] = obj;
}
};
Can anyone help me understand how to modify the mex file so that it accepts an array of EmployeeID and iterate through the elements of the array in C++ mex and does something simple, like printing the name of field for each array?
Any help is much appreciated.

Accepted Answer

Ali Behboodian
Ali Behboodian on 24 Nov 2023
This was documented on the same page but I have missed it.
The trick is mentioned here:
Get Property Value from Object Array
If the input to the MEX function is an object array, call getProperty with index of the object in the array whose property value you want to get. For example, this code snippet returns the value of the Name property for the fourth element in the object array, objectArray.
matlab::data::Array objectArray(inputs[0]);
matlab::data::CharArray propName = matlabPtr->getProperty(objectArray, 3, u"Name");

More Answers (0)

Community Treasure Hunt

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

Start Hunting!