How does sprintf ('% d', A) - '0' work?

I was looking for a way to separate the digits of an array in Matlab ie if A = 1024 , then I would like it to be A = [1, 0, 2, 4] .

I searched the net and found this code (also published in the header):

 sprintf('%d',A) - '0' 

which transformed [1024][1, 0, 2, 4] .

This solved my problem, but I did not understand it, especially the part - '0' . can someone explain how this works?

Also, if I write sprintf('%d',A) + '0' (for A = [1024] ) in the MATLAB command window, then it showed the following:

  97 96 98 100 

This puzzled me even more, can anyone explain this?

+4
source share
2 answers

It uses automatic casting from a char array to a double array when the - operator - . Remember that each character has an ascii value, so if you type double('0') at the command line and you will see that you will get 48 as the answer. So far, double('1024') gives you

 ans = 49 48 50 52 

sprintf('%d', A) just convert the integer to a string (i.e. a char array). Minus discards both sides to double, the result is

double('1024') - double('0')

which the

[49, 48, 50, 52] - [48]

which ends as [1,0,2,4]

From here it should be clear why the addition of '0' led to [97, 96, 98, 100]

+4
source

The sprintf('%d',A) command sprintf('%d',A) converts the integer A=1024 to the string representation of the number, '1024' .

Also, the string in matlab really is an array of characters, so if A = '1024' then A(1) = '1' .

The rest of the explanation follows from @Dan's answer. When numeric operations ( + - * / mod ^ ...) are applied to character arrays, they are converted to an equivalent numeric representation according to ASCII code, saving the array format as a double type.

+2
source

Source: https://habr.com/ru/post/1495906/


All Articles