I need help coding in MATLAB I need to creating a script/function file that will
ID: 645194 • Letter: I
Question
I need help coding in MATLAB
I need to creating a script/function file that will convert from binary to decimal and vice versa without using the built-in matlab commmands.
So far, I have
n= input('Enter Binary Number= ', 's');
m=length(n)
dec = 0;
i = 1;
while i < m + 1
dec = dec + str2num(n(i)) * 2^(m - i);
i = i + 1;
end
fprintf('The Decimal Value is %i',dec)
But is there a way to do this without the using string to number?
And to convert from decimal for binary, I'm not even sure where to begin.
Please explain steps.
Explanation / Answer
Answer:
Function to convert from binary to decimal and vice versa without using the built-in matlab commmands:
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;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.