In: Advanced Math
Write a user-defined MATLAB function that converts real numbers in decimal form to binary form. Name the function b = deciTObina (d), where the input argument d is the number to be converted and the output argument b is a 30-element-long vector with 1s and 0s that represents the number in binary form. The first 15 elements of b store the digits to the left of the decimal point, and the last 15 elements of b store the digits to the right of the decimal point. If more than 15 positions are required in the binary form for the digits to the right of the decimal point, the digits should be chopped. If the number that is entered as d is larger than can be stored in b, the function should display an error message. Use the deciTObina in the Command Window to convert the numbers 85.321, 0.00671, and 3006.42.
%%% Matlab function
function [b] = deciTObin(d)
i=15;
j=16;
dn=floor(d); %%% integer part
dd=d-dn; %%% decimal part
for n=1:15
if (d > 2^(15))
disp('Number is too
large to store in 15 digit');
break;
else
%%% Left part
b(i)=mod(dn,2);
dn=floor(dn/2);
i=i-1;
%%% right part
dd=dd*2;
if ( dd > 1 || dd ==1
)
b(j)=1;
dd=dd-1;
else
b(j)=0;
end
j=j+1;
end
end
end
%%%%
clc;
clear all;
close all;
d=85.321;
b=deciTObin(d);
b'
d=0.00671;
b=deciTObin(d);
b'
d=3006.42;
b=deciTObin(d);
b'
OUTPUT:
ans =
0
0
0
0
0
0
0
0
1
0
1
0
1
0
1
0
1
0
1
0
0
1
0
0
0
1
0
1
1
0
ans =
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
1
1
0
1
1
ans =
0
0
0
1
0
1
1
1
0
1
1
1
1
1
0
0
1
1
0
1
0
1
1
1
0
0
0
0
1
0
>>