If I have a string in matlab, I can convert it to a vector of ASCII codes using double
:
>> my_string = 'asd';
>> double(my_string)
ans =
97 115 100
How can I go back the other way? i.e., if I have an ASCII code in a MATLAB vector, how can I create the corresponding string?
e.g
ascii_codes = [97 115 100];
should be converted to...
my_string = 'asd'
X = str2num( txt ) converts a character array or string scalar to a numeric matrix. The input can include spaces, commas, and semicolons to indicate separate elements. If str2num cannot parse the input as numeric values, then it returns an empty matrix.
str = string( A ) converts the input array to a string array. For instance, if A is numeric vector [1 20 300] , str is a string array of the same size, ["1" "20" "300"] . str = string( A , dateFmt ) , where A is a datetime or duration array, applies the specified format, such as "HH:mm:ss" .
You can create strings using double quotes, such as str = "Greetings friend" . To convert data to string arrays, use the string function.
s = num2str( A ) converts a numeric array into a character array that represents the numbers. The output format depends on the magnitudes of the original values. num2str is useful for labeling and titling plots with numeric values.
How about char
(documentation)? Eg char(ascii_codes)
?
A great alternative to the char function, in my opinion, is the native2unicode function. It handles many different encoding schemes, allowing you to explicitly specifying the one to be used through its second input argument:
unicodestr = native2unicode(bytes, encoding) converts bytes to a Unicode representation with the assumption that bytes is in the character encoding scheme specified by encoding. The input argument encoding must have no characters ('') or it must be a name or alias for an encoding scheme. Some examples are 'UTF-8', 'latin1', 'US-ASCII', and 'Shift_JIS'. If encoding is unspecified or has no characters (''), the default encoding scheme is used. encoding can be a character vector or a string scalar.
Usage example:
>> ascii_codes = [97 115 100];
>> my_string = native2unicode(ascii_codes,'ASCII')
my_string =
'asd'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With