I'm looking for a quick way to get a variat of dec2bin
in Matlab such that it'll return a logical variable vector. For example given a number n=8
the output will be [1,0,0,0].
How can I do that?
The simplest way is to simply explode the binary representation returned by dec2bin
(which is already a string!):
dec2bin(n) == '1'
For n = 8
this returns a logical vector
1 0 0 0
This will also work if n
is a vector of numbers.
Since string '1' is char(49) and string '0' is char(48) you can use:
bin = dec2bin(dec) - 48;
This will output the result as an array of doubles, since you are performing an arithmetic operation over an array (the string coming from «dec2bin» is considered an array in Matlab)
If you want to convert very high integers to binary, I recommend using this code:
bin = mod(floor(dec.*2.^-(floor(log2(dec)):-1:0)),2);
In order to convert binary vector to decimal:
dec = sum(bin.*2.^((length(bin)-1):-1:0));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With