Write a function (Not a built-in function) that converts a given number n in base 2 to base 10
4 views (last 30 days)
Show older comments
Suppose n is a base2 number, which will be put in as a vector (i.e., 10100 = [1 0 1 0 0]). I'm trying to write a code than converts that number to a base10 number. I ran it and got the following error: Out of memory. The likely cause is an infinite recursion within the program.
Error in base2 (line 4) y(i) = base2(i)*(2^(length(n)-i));
What am I doing wrong? The code is:
function [base10] = base2(n)
y = [];
for i = 1:length(n)
y(i) = base2(i)*2^(length(n)-i);
base10 = sum(y);
end
end
Answers (3)
Guillaume
on 1 Sep 2016
Learn to use the debugger. Step through your code line by line, look at how the variables change and where the code go at each step. You'll quickly see where it goes wrong.
You're using recursion (your function calls itself), but there's nothing in your code to stop the recursion. Look at your loop, the first step is to call base2 again.
Once you've fixed that, a more minor issue is that you recalculate the final sum in the loop, when you only need to do it once, when the loop is finished.
0 Comments
George
on 1 Sep 2016
There's a builtin function called bin2dec which turns a binary string into a decimal number. So if you convert the data into a string you can use bin2dec.
aa = [1 0 1 0];
bb = num2str(aa);
result = bin2dec(bb)
result =
10
1 Comment
Thorsten
on 1 Sep 2016
There is a nice oneliner that solves the problem:
base10 = 2.^(numel(n)-1:-1:0)*n(:);
If you use it, your task is to understand it, in case your advisor asks...
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices 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!