Info
此问题已关闭。 请重新打开它进行编辑或回答。
Is it possible to create an inline function which gives back n binary digits of a number in a vector?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Walter Roberson
2017-12-12
Subtract '0' (the character for the digit 0) from dec2base or dec2bin
7 个评论
Stephen23
2017-12-18
编辑:Stephen23
2017-12-18
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
2017-12-18
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 个评论
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!