필터 지우기
필터 지우기

Write a function (Not a built-in function) that converts a given number n in base 2 to base 10

조회 수: 5 (최근 30일)
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

답변 (3개)

Guillaume
Guillaume 2016년 9월 1일
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.

George
George 2016년 9월 1일
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

Thorsten
Thorsten 2016년 9월 1일
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...

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by