Info
Questa domanda è chiusa. Riaprila per modificarla o per rispondere.
Is it possible to create an inline function which gives back n binary digits of a number in a vector?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (2)
Walter Roberson
il 12 Dic 2017
Subtract '0' (the character for the digit 0) from dec2base or dec2bin
7 Commenti
Stephen23
il 18 Dic 2017
Modificato: Stephen23
il 18 Dic 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
il 18 Dic 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 Commenti
Questa domanda è chiusa.
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!