フィルターのクリア

Recursive binary to decimal function

6 ビュー (過去 30 日間)
Rick
Rick 2014 年 8 月 12 日
回答済み: Geoff Hayes 2014 年 8 月 13 日
Hello, I'm trying to write a function that will convert binary to decimal using recursion, but I am having difficulty getting the recursive part.
function y = Bin2dec(BA)
n = length(BA);
if n == 1
y = BA;
else
y = Bin2dec(BA(n-1));
end
  1 件のコメント
Michael Haderlein
Michael Haderlein 2014 年 8 月 12 日
編集済み: Michael Haderlein 2014 年 8 月 12 日
I have no idea what kind of conversion you want to do here, but maybe the error is that in case of the recursion (so, the if condition is false), you restart your function not with a limited array but only with one value. Most likely, you need to use
...
else
y = Bin2dec(BA(1:n-1));
end
...

サインインしてコメントする。

採用された回答

Geoff Hayes
Geoff Hayes 2014 年 8 月 13 日
Rick - recursion is not really necessary to solve this problem. You can just iterate over each element in the input vector and sum the values according to
function y = myBin2dec(BA)
y = 0;
n = length(BA);
% move left to right in binary sequence
for k=n:-1:1
y = y + BA(n-k+1)*2^(k-1);
end
end
with
myBin2dec([0 0 0 1])
ans =
1
myBin2dec([1 0 0 0])
ans =
8
A recursive version could look like
function y = myBin2dec(BA)
y = 0;
n = length(BA);
if n>0
y = BA(1)*2^(n-1) + myBin2dec(BA(2:end));
end
end
and would return the same results as the previous example.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by