Info
Cette question est clôturée. Rouvrir pour modifier ou répondre.
Is it possible to create an inline function which gives back n binary digits of a number in a vector?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
The input parameters must be the number x itself, and the number of digits (N). So dec2base(x,2) is not good, because its output is a string, and because 0-s are truncated. So instead of '101' I need [1 0 1], and instead of '1' I need [0 0 1], if N = 3
0 commentaires
Réponses (2)
Walter Roberson
le 12 Déc 2017
Subtract '0' (the character for the digit 0) from dec2base or dec2bin
7 commentaires
Stephen23
le 18 Déc 2017
Modifié(e) : Stephen23
le 18 Déc 2017
Some character vector minus the character zero?
This just subtracts a scalar number from a vector. What is the problem with that?
Everything on your computer is stored as numbers: all of those nice colors, happy music, and (most importantly for you right now) all of the text characters. A MATLAB char array is therefore just an array of numbers, which normally get interpreted as some glyph when it is displayed (and of course we all know that how something is displayed and how something is stored in memory are two quite different things). Because that char vector is actually an array of numbers you can simply perform numeric operations on them. Most of the time this is rather meaningless, but sometimes it has some neat properties, such as the answer you were given to get the numeric digits from a string of digit characters.
You can get the character vector's numeric values using either of these:
double(S)
+S
and for the zero character:
double('0')
+'0'
And then the reason why this answer works is pretty obvious. You could have investigated this yourself without destroying your computer: did you know that experimenting with MATLAB is encouraged, and will help you to learn?
Guillaume
le 18 Déc 2017
You can either use
V = dec2bin(x, N) - '0'
as per Walter's answer or
V = bitget(x, N:-1:1)
The advantage of the first version is that it works with non-scalar x (and gives you a 2d matrix). The advantage of the second method is that it probably is a bit faster for scalar inputs.
0 commentaires
Cette question est clôturée.
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!