フィルターのクリア

Convert base 2 to base 10 using loop

8 ビュー (過去 30 日間)
Mary Jeppson
Mary Jeppson 2016 年 12 月 8 日
コメント済み: Mary Jeppson 2016 年 12 月 8 日
I've written this loop, but it produces a value of 128 for every number in the mult array instead of going from 128 to 64 to 32 etc. Can anyone tell me why? Thank you for your help!
%Convert base 2 numbers to base 10
base2 = [1 0 1 1 0 0 1];
mult = ones(1,length(base2))
for k = 1:length(base2)
mult(1,k) = mult(1,k)*2^(length(base2-k))
k = k+1
end
base10 = base2*mult'

採用された回答

dbmn
dbmn 2016 年 12 月 8 日
There are two errors in your code
1) Bracket at wrong position (causes your problem to stay at 128 all the time)
mult(1,k) = mult(1,k)*2^(length(base2)-k)
2) Obsolete Increase in loop variable. If you have a for loop, Matlab increases the variable by itself (check the docu). So the following has no effect, since Matlab simply overwrites your changes.
k = k+1
  1 件のコメント
Mary Jeppson
Mary Jeppson 2016 年 12 月 8 日
I see! Thank you for your help.
Mary

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by