# Why is my code seemingly ignoring some of the for loop commands?

3 ビュー (過去 30 日間)
Sydney 2024 年 5 月 12 日
コメント済み: Voss 2024 年 5 月 12 日
Hello, I'm new to MATLAB and I'm trying to create a user-defined function that acts like bin2dec using manual conversion of binary to decimal integer, but I can't figure out why I'm getting outputs of "1" or no output value for x altogether. Can someone please help me understand what's wrong with my code? Thank you!!
% mybin2dec takes one single valued text input argument representation of a binary number and converts it to a decimal integer
function b=mybin2dec(x)
x=input('Enter a binary number as a text input: ', 's')
str2num(x)
n=length(x)-1
for y=[1:length(x)]
if x(y)==49
d=(1*(2^n))
n=n-1
elseif x(y)==48
d=(0*(2^n))
n=n-1
end
end
sum(d)

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

### 採用された回答

Walter Roberson 2024 年 5 月 12 日
function b=mybin2dec(x)
You do not assign anything to b . Your code will error unless you do not assign the result of mybin2dec() to a variable and you supress the default output.
d=(1*(2^n))
You overwrite all of d within each loop iteration. The final d that will be assigned is whatever it is assigned in the last iteration.
Hint:
if x(y)==49
can be written as
if x(y)=='1'
##### 1 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
Sydney 2024 年 5 月 12 日
Thank you so much for your help! Silly oversight on my part, it works now!

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

### その他の回答 (1 件)

Voss 2024 年 5 月 12 日
d is computed anew on each iteration of the for loop; thus after it's done the result you see is the last d that was computed, either 0 or 1. You should be adding each d to the sum of all the previous d's that were already calculated.
I see you have sum(d) at the end, but as d is a scalar, that doesn't really do anything. I guess that means that d is intended to be a vector the same length as x, in which case you should be storing d(y) instead of d inside the loop when you calculate it.
##### 2 件のコメントなしを表示なしを非表示
Sydney 2024 年 5 月 12 日
Thank you very much! I appreciate your help!!
Voss 2024 年 5 月 12 日
You're welcome!

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

### カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

### Community Treasure Hunt

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

Start Hunting!

Translated by