Double into Matrix of its Digits

4 次查看(过去 30 天)
Rightia Rollmann
Rightia Rollmann 2016-8-12
编辑: dpb 2016-8-13
How does the function B work? What does the symbol – and the symbol ‘0’ do for the function?
A = [ 123; 456; 789 ]
B=num2str(A)-'0'

回答(1 个)

dpb
dpb 2016-8-12
编辑:dpb 2016-8-13
Did you try it and see???
>> num2str(123)
ans =
123
>> whos ans
Name Size Bytes Class Attributes
ans 1x3 6 char
>> ans-'0'
ans =
1 2 3
>> whos ans
Name Size Bytes Class Attributes
ans 1x3 24 double
>>
Matlab is not strongly typed; it will convert from one variable type to another readily; num2str turns the number as a double into its string representation of N digits in length; that internally is stored as array of integer with the coded ASCII value corresponding to the position in the ASCII table. "-" is just the same old subtraction operator; subtracting the value of an ASCII zero from each character in the string. Doing math on a char does convert it by Matlab syntax rules into a number so since there are three characters in the string, you end up with an array of default double of that length each containing the corresponding numeric value of the character it represents.
ADDENDUM
Or, explicitly, what's happening internally is simply
>> double('0':'9')
ans =
48 49 50 51 52 53 54 55 56 57
>> ans-48
ans =
0 1 2 3 4 5 6 7 8 9
>>
END ADDENDUM
This can also be accomplished by
>> n=123;
>> sscanf(sprintf('%d',n),'%1d')
ans =
1
2
3
>>
The practical reason for the idiom as used with num2str is that it is "vectorized" for arrays while sscanf and friends aren't as readily applied to arrays.

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by