Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from ASCII code to string in MATLAB

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'
like image 445
Bill Cheatham Avatar asked Mar 04 '11 11:03

Bill Cheatham


People also ask

How do I convert a string to a number in MATLAB?

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.

How do I convert an array to a string in MATLAB?

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" .

How do you make a string in MATLAB?

You can create strings using double quotes, such as str = "Greetings friend" . To convert data to string arrays, use the string function.

How do I convert a number to a character in MATLAB?

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.


2 Answers

How about char (documentation)? Eg char(ascii_codes)?

like image 168
Marcus Frödin Avatar answered Oct 11 '22 19:10

Marcus Frödin


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'
like image 35
Tommaso Belluzzo Avatar answered Oct 11 '22 20:10

Tommaso Belluzzo