- https://mathworks.com/help/matlab/apiref/matlab.data.string.html
- https://mathworks.com/help/matlab/apiref/matlab.data.chararray.html
- https://mathworks.com/help/matlab/apiref/matlab.data.stringarray.html
- https://mathworks.com/help/matlab/apiref/matlab.data.optional.html
How to convert a matlab::data::Array to string
6 views (last 30 days)
Show older comments
i am intefacing one library with matlab using MEX
i am acessing a variable from workspace using
matlab::data::Array varName = matlabPtr->getVariable(u"varName")
i want to convert this varName to string
i am using 2018a version of MATLAB and entirely new to MATLAB
please help
0 Comments
Answers (1)
Madheswaran
on 29 May 2025
Hi Hareesh,
The matlab::data::Array is a generic C++ class that can represent all types of MATLAB arrays. I am assuming that your variable 'varName' is stored as a character array in the MATLAB workspace.
For character arrays, you can convert them to std::string using the following approach:
matlab::data::CharArray varName = matlabPtr->getVariable(u"varName");
std::string str = varName.toAscii();
If your variable 'varName' is stored as a matlab::data::StringArray and you need to extract a string from a specific index, you can use this method:
matlab::data::StringArray varName = matlabPtr->getVariable(u"varName");
matlab::data::MATLABString str_ml = varName[idx];
if (str_ml.has_value()) {
matlab::data::String str_utf16 = str_ml;
std::string str(str_utf16.begin(), str_utf16.end());
}
As mentioned in the documentation, matlab::data::String represents std::basic_string<char16_t>, which means it uses 16-bit characters. The conversion method shown above works well for ASCII characters. If you need to handle Unicode characters properly, you may need to use additional conversion functions.
For detailed information, please refer to the following documentation:
Hope this helps!
0 Comments
See Also
Categories
Find more on Characters and Strings 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!