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 commentaire

per isakson
per isakson le 10 Oct 2015
Modifié(e) : per isakson le 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

Connectez-vous pour commenter.

Réponses (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'
Walter Roberson
Walter Roberson le 10 Oct 2015

0 votes

dec2bin([1 0 1 1 0])'

2 commentaires

DavHor
DavHor le 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
dec2bin(123)
If you have values that are not integral then there is no standard way of converting them to binary for printed representation.

Connectez-vous pour commenter.

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.

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by