coverting string to ascii value in Matlab

292 ビュー (過去 30 日間)
fima v
fima v 2020 年 10 月 29 日
編集済み: per isakson 2020 年 11 月 2 日
Hello the letter 'a' is 61 why in matlab i get NAN?
  1 件のコメント
Stephen23
Stephen23 2020 年 10 月 29 日
"Hello the letter 'a' is 61 why in matlab i get NAN?"
Sort of... just writing "61" without any indication of the base would lead most people to quite reasonably assume that you mean base 10, i.e. decimal. But in fact lower-case 'a' is:
  • 61 hexadecimal
  • 97 decimal

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2020 年 10 月 29 日
編集済み: Stephen23 2020 年 10 月 29 日
"the letter 'a' is 61 why in matlab i get NAN?"
Because that is the wrong way to get the ASCII value (or character code, to be precise) of the string class.
And also the wrong value to expect as an output.
Here are two correct ways to get the character code of a character in a string:
var = "a";
double(char(var))
ans = 97
double(var{1})
ans = 97
These both return the correct decimal character code of the 'a' character (i.e. Unicode "Latin Small Letter A").
Explanation of the two mistakes in your approach:
  1. a string array is basically a container array of character vectors. This means that in order to get the character code of any character inside a string you first need to get the characters, not just the container object (a container object has no character code). This is explained here in the section "Access Characters Within Strings": https://www.mathworks.com/help/matlab/matlab_prog/create-string-arrays.html
  2. the function str2double converts the representation of a number into a numeric value, for example, it will convert '1.2' into the double 1.2, but it has nothing to do with character codes. If the string does not contain a valid number representation then str2double returns NaN (and in your example 'a' is definitely not a valid representation of a number). The documentation explains the correct way to get character codes here in quite a lot of detail and with plenty of examples too: https://www.mathworks.com/help/matlab/matlab_prog/unicode-and-ascii-values.html

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by