MATLAB: Converting binary to decimal and vice versa, please help!!

binaryconversiondecimalhomework

I'm having trouble converting strings that represent binary numbers to decimal and vice versa. The main issue is that I'm unsure of how to deal with the decimal point, say converting -11.11 to decimal. This is a homework assignment, so I'm not allowed to use the built in functions.
Here's my code for one of the two:
function decimal= mybin2real(binarystring)
decimal = 0;
for i = 1 : length(binarystring)
decimal = decimal + str2num(binarystring(i)) * 2^(length(binarystring) - i);
end
decimal
end
I was thinking about finding where the decimal point was using strfind, but i'm not sure how to implement it in the matlab code.

Best Answer

Here I have simply fixed your code. You were really close!
function decimal= mybin2real(binarystring)
% Converts an input string of 1s and 0s to a number.
Ind = strfind(binarystring, '.');
L = length(binarystring);
if isempty(Ind)
Ind = L+1;
end
Num1 = binarystring(1:Ind-1);
LN1 = length(Num1);
Num2 = binarystring(Ind+1:end);
LN2 = length(Num1);
dec1=0;
for ii = 1 : LN1
dec1 = dec1 + str2double(Num1(LN1-ii+1)) * 2^(ii-1);
end
dec2=0;
for ii = 1 : length(Num2)
dec2 = dec2 + str2double(Num2(ii)) * 2^-(ii);
end
decimal=dec1+dec2;