Effacer les filtres
Effacer les filtres

Double into Matrix of its Digits

4 vues (au cours des 30 derniers jours)
Rightia Rollmann
Rightia Rollmann le 12 Août 2016
Modifié(e) : dpb le 13 Août 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'

Réponses (1)

dpb
dpb le 12 Août 2016
Modifié(e) : dpb le 13 Août 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.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by