필터 지우기
필터 지우기

If I try to use `sprintf` to format a string as numeric, why does a different number get passed?

조회 수: 29 (최근 30일)
When I try to format strings with numeric values using sprintf, I notice that if I forget to change the value that I'm trying to pass from a string to numeric, then a different value is passed.
For example, I'm trying to format a string using the value in C.
C='10';
% Forget to convert to number
sprintf('%d %f', C)
ans =
'49 48.000000'
If I try to convert to a number using double, I get
double(C)
ans =
49 48
which matches the sprintf output. If I use str2num, then everything works as I expect.
sprintf('%d %f', str2num(C))
ans =
'10 '
Why does this happen?
  댓글 수: 1
Stephen23
Stephen23 2022년 9월 20일
편집: Stephen23 2022년 9월 20일
"Why does this happen?"
Everything on a computer is stored as a number. The character vector '10' consists of two characters:
  • '1' , which is stored as the number 49
  • '0' , which is stored as the number 48
DOUBLE gives you those chararacter codes, as does converting them to numeric (basically just a typecast).

댓글을 달려면 로그인하십시오.

답변 (2개)

Star Strider
Star Strider 2022년 9월 20일
Using:
C='10';
‘C’ is a character array, not actually a number. The conversion to double results in the ASCII codes for the individual character elements, ‘1’ and ‘0’ so if you instead used the '%s' format the result would be:
C='10';
sprintf('%s',C)
ans = '10'
The char function can help to explain this.
.

Jérôme
Jérôme 2022년 9월 20일
When you write
C='10';
C is a char array, i.e. an array with two elements of class char, which are '1' and '0'.
These are characters, which are (like any type of variable) encoded with numbers behind.
The encoding used here is probably UTF-8 / Unicode, where '1' is stored as 49 and '0' as 48 (see https://en.wikipedia.org/wiki/List_of_Unicode_characters#Basic_Latin).
In the same way, you would get the following and you can check this value in the link above:
D = 'λ';
double(D)
ans = 955
When you write
sprintf('%d %f', C)
ans = '49 48.000000'
you are telling the function to expect numbers, so it interprets the content stored (49 and 48) as numbers, which is why it shows them. Whereas if you write
sprintf('%c', C)
ans = '10'
you are telling the function to expect characters, so it interprets the content stored (49 and 48) as characters encoded with UTF-8 / Unicode, then it shows you the characters.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by