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
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.
0 件のコメント
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
1 件のコメント
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...
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!