In: Computer Science
1.) Write a function, base2tobase10 that has a single input, a vector containing 1,s and 0 's representing a binary number. For example the binary number 01101011 would be represented by the vector [ 0, 1, 1, 0, 1, 0,1, 1]. Your function should return a single output,the base 10 equivalent of the base 2 number.
First, your function must check the input vector and detremine if any of the vector elemnets are not a 0 or a1. If they are not, print error message "Please enter only ones and 0's" using fprintf() and exit gracefully to the console prompt using "return"
Reall that in Base 10
mySum = 4+70+300+2000+10000
So , in base 2
MySum = 1+2+0+8+0+32+64+0
Test code DO NOT CHANGE ANY OF THIS CODE
score = 0;
% -------------TEST base2tobase10 ------------------
rng(123456);
myBin = [ 1 1 0 1 1];
try
myBase10 = base2tobase10(myBin);
catch
warning('Problem using function. Assigning a value of 0.');
myBase10 = 0
end
if myBase10 == bin2dec(num2str(myBin))
fprintf('first test of base2tobase10 passed')
else
fprintf('first test of base2tobase10 failed')
end
myBin = [1];
try
myBase10 = base2tobase10(myBin);
catch
warning('Problem using function. Assigning a value of 0.');
myBase10 = 0
end
if myBase10 == bin2dec(num2str(myBin))
fprintf('second test of base2tobase10 passed')
else
fprintf('second test of base2tobase10 failed')
end
insert your code in the box below
%insert your code here
Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate
the question. Thank You So Much.
Function First
base2tobase10.m
function res = base2tobase10( v )
res = 0;
for k=length(v):-1:1
res = res + power(2,k-1)*v(k);
end
end
Main.m
clc
clear
rng(123456);
myBin = [ 1 1 0 1 1];
try
myBase10 = base2tobase10(myBin);
catch
warning('Problem using function. Assigning a value of 0.');
myBase10 = 0;
end
if myBase10 == bin2dec(num2str(myBin))
fprintf('first test of base2tobase10 passed')
else
fprintf('first test of base2tobase10 failed')
end
myBin = [1];
fprintf("\n");
try
myBase10 = base2tobase10(myBin);
catch
warning('Problem using function. Assigning a value of 0.');
myBase10 = 0;
end
if myBase10 == bin2dec(num2str(myBin))
fprintf('second test of base2tobase10 passed')
else
fprintf('second test of base2tobase10 failed')
end
output