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

조회 수: 5 (최근 30일)
Hareesh Kumar
Hareesh Kumar 2019년 1월 31일
답변: Madheswaran 2025년 5월 29일
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

답변 (1개)

Madheswaran
Madheswaran 2025년 5월 29일
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!

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by