Bill Cheatham
Bill Cheatham

Reputation: 11917

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'

Upvotes: 8

Views: 46664

Answers (2)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23685

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'

Upvotes: 1

Marcus Frödin
Marcus Frödin

Reputation: 12882

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

Upvotes: 20

Related Questions