Clear Filters
Clear Filters

Double into Matrix of its Digits

4 views (last 30 days)
Rightia Rollmann
Rightia Rollmann on 12 Aug 2016
Edited: dpb on 13 Aug 2016
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'

Answers (1)

dpb
dpb on 12 Aug 2016
Edited: dpb on 13 Aug 2016
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.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!