Write a user dened Matlab function that converts integers written in decimal form to binary form. Name the function b = Bina(d), where the input argument d is the integer to be converted and the output argument b is a vector with ones and zeros that represents the number in binary form. The largest number that could be converted with the function should be a binary number which 16 ones. If a large number is entered as d, the function should display an error message. Use the function to convert the following numbers: (a) 100 ( b) 1002 (c) 52601 (c) 200,090

Respuesta :

Answer:

function b = Bina (d)

%the largest number is

larg=0;

for i=1:16

larg=larg+2^(i-1);

end

%addres of non-zero elements in bin

num=[];

%do the loop while d is not 0

while d & d<=larg

elem=floor(log(d)/log(2));

num=[num elem];

d=d-2^elem;

end

if isempty(num)==0

b=zeros(1, max(num+1));

b(num+1)=ones(1, length(num));

fprintf('The number is: \n');

fprintf('%d', b(:));fprintf('\n');

else

b=-1;

fprintf('The number is to big.\n');

end

end

Explanation:

a) Bina(100);

The number is: 0010011

b) Bina(1002);

The number is: 0101011111

c) Bina(52601);

The number is: 1001111010110011

d) Bina(200090);

The number is to big.

The code written in MATLAB is shown in the answer section. While the call to the function and the answer is shown in the explanation section.

The MATLAB code is commented (%) on some part. The code start by defining the function Bina(d) then it has a loop that loop from 1 to 16 but uses the value of i from 0 - 15; this is done to convert the given argument in the function to base 10.