- sprintf creates a string from a numeric
- sscanf can read digits from a string
I want to change binary to an array and vice vera
3 views (last 30 days)
Show older comments
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
on 10 Oct 2015
Edited: per isakson
on 10 Oct 2015
Is this homework? I assume that "binary" is a string. Hint:
Answers (3)
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'
0 Comments
Walter Roberson
on 10 Oct 2015
dec2bin([1 0 1 1 0])'
2 Comments
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.
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.
0 Comments
See Also
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!