Binary sequence from a vector to a variable

조회 수: 2 (최근 30일)
Cristian Mancera
Cristian Mancera 2016년 3월 15일
댓글: Andrei Bobrov 2016년 3월 15일
Hi!I have a binary sequence and I want to save it in a variable. How could I do it? Like this:
a= [1,0,0,1,0] -> ? -> b=10010
Thank you very much

답변 (4개)

Ced
Ced 2016년 3월 15일
But a IS the binary sequence save in a variable? If you want to transform this into some decimal representation of the same digits...
represent_bin_as_dec = @(x)sum(x.*10.^(length(x)-1:-1:0),2);
a = [ 1 0 0 1 0 ];
b = represent_bin_as_dec(a)
Cheers
  댓글 수: 2
John D'Errico
John D'Errico 2016년 3월 15일
bin2dec
Ced
Ced 2016년 3월 15일
Yep, saw the answer. Good to know, thanks!
Although I think I still prefer to stay in the number realm rather than corrupting this mathematical purity with some characters, haha.
Guillaume's answer looks cleaner than mine here... but I just like to see the inner working of things. I guess that internally, polyval does more or less the same thing, plus of course all the input parsing and such.
I always enjoy having multiple answers for the same question. That's when we really learn new things :).

댓글을 달려면 로그인하십시오.


John D'Errico
John D'Errico 2016년 3월 15일
a already is a variable!
That sequence is a vector of information. As such, you need to store it in a vector.
1. You can convert it to a string. But it will still be a vector, just a vector of character elements. So
b = char(a+'0')
b =
10010
2. You can convert it to an integer, as long as there are not more than 64 bits of information, if you will store it in a double.
b = bin2dec(char(a+'0'))
ans =
18
bin2dec only works up to 52 bits of course. Beyond that, you would need to use a conversion into uint64.

Guillaume
Guillaume 2016년 3월 15일
Another option
a = [1 0 0 1 0]
b = polyval(a, 10) %decimal representation of the same digits
Note that I don't see how b is useful, since you can't use it to perform any arithmetic. The true number represented by a is:
c = polyval(a, 2)
  댓글 수: 1
John D'Errico
John D'Errico 2016년 3월 15일
A nice trick for base conversions. Of course, still limited to double as such. But still nice.

댓글을 달려면 로그인하십시오.


Cristian Mancera
Cristian Mancera 2016년 3월 15일
I used bin2dec, it is very simple and exactly what I needed, thanks to all of you :)
  댓글 수: 1
Andrei Bobrov
Andrei Bobrov 2016년 3월 15일
In it case, please accept answer by John D'Errico.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by