How to convert a matlab::data::Array to string

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

Antworten (1)

Madheswaran
Madheswaran am 29 Mai 2025

0 Stimmen

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:
  1. https://mathworks.com/help/matlab/apiref/matlab.data.string.html
  2. https://mathworks.com/help/matlab/apiref/matlab.data.chararray.html
  3. https://mathworks.com/help/matlab/apiref/matlab.data.stringarray.html
  4. https://mathworks.com/help/matlab/apiref/matlab.data.optional.html
Hope this helps!

Kategorien

Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2018a

Gefragt:

am 31 Jan. 2019

Beantwortet:

am 29 Mai 2025

Community Treasure Hunt

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

Start Hunting!

Translated by