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

답변 (2개)

Walter Roberson
Walter Roberson 2017년 12월 12일
Subtract '0' (the character for the digit 0) from dec2base or dec2bin
  댓글 수: 7
Stephen23
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?
Mr M.
Mr M. 2017년 12월 18일
"did you know that experimenting with MATLAB is encouraged"
Yes, thanks! BUT in general, finding solutions on the forum could be important for others also

Guillaume
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.

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by