I want to change binary to an array and vice vera

3 views (last 30 days)
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
per isakson
per isakson on 10 Oct 2015
Edited: per isakson on 10 Oct 2015
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)

Image Analyst
Image Analyst on 11 Oct 2015
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'

Walter Roberson
Walter Roberson on 10 Oct 2015
dec2bin([1 0 1 1 0])'
  2 Comments
DavHor
DavHor on 10 Oct 2015
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
Walter Roberson
Walter Roberson on 10 Oct 2015
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.


Star Strider
Star Strider on 10 Oct 2015
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

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!