I want to change binary to an array and vice vera

I need to be able to change [1 0 1 1 0] to 10110
also its required that i do the opposite eg. 10110 to [1 0 1 1 0]
This has to work for all binary numbers and also for decimal numbers, I have done a lot of research and trying different things but I have not found any solution.
For the assignment I only have one line to spare but if needs be I can cut somewhere else if i need to,
also would anybody be able to explain what a string is, i think its related to what I'm trying to achieve,
thanks.

1 Comment

Is this homework? I assume that "binary" is a string. Hint:
  • sprintf creates a string from a numeric
  • sscanf can read digits from a string
"explain what a string is" &nbsp see String handling

Sign in to comment.

Answers (3)

This little trick is shown frequently in this forum:
% Start with a logical variable vector
m = logical([1 0 1 1 0]) % Change to '10110'
% First convert to a string.
string = sprintf('%d', m)
% Convert the string back to a logical.
logicalVector = string - '0'
dec2bin([1 0 1 1 0])'

2 Comments

sorry i have the binary and decimal numbers found i need to be able to change how they are displayed eg in a number or array
dec2bin(123)
If you have values that are not integral then there is no standard way of converting them to binary for printed representation.

Sign in to comment.

To change a decimal scalar or a concatenated binary number (represented as a scalar) into a vector of its digits, this works for positive integers:
b = 10110; % Binary String As Double Scalar
lb = ceil(log10(b)); % Length Of ‘b’
for k1 = 1:lb
d(k1) = rem(b,10);
b = floor(b/10);
end
d = flip(d) % Vector Of ‘b’
d =
1 0 1 1 0
There are likely more efficient and robust methods. This is probably the most obvious.

Categories

Asked:

on 10 Oct 2015

Answered:

on 11 Oct 2015

Community Treasure Hunt

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

Start Hunting!