Sei sulla pagina 1di 1

key

Name or Random Student Number:_____________________________


ChBE 2120, Numerical Methods, Paravastu Section, Fall 2018
Quiz 1
1) (5 points) The following function is meant to test whether or not a list of numbers contains only zeros, but
Anant screwed it up. The input list L is assumed to contain at least one number. Correct the mistakes in this
MATLAB function.
function [ ZeroList ] = TestIfZeroList( L )
%Input: L is a list of numbers of any length greater than or equal to 1.
%Output: ZeroList will be 1 if L contains only zeros and 0 otherwise.
if L(1) ~= 0 %~= means NOT EQUAL

1011
ZeroList = 1;
elseif length(L) > 2
ZeroList = TestIfZeroList(L(2:end));
else
ZeroList = 1;
end
end

2) (5 points) There is a simpler way to accomplish what TestIfZeroList does in Problem 1 above. Write a new function
to accomplish the task in the following 3 steps:
Step 1: Square every number in L. The resultant list can only contain positive numbers and zeros.
Step 2: Add up every number in this new list. To do this, you may use MATLAB’s built-in “sum”
function.
Step 3: If the resultant sum is greater than 0, then there must have been at least one nonzero element in L.
Implement Steps 1-3, starting with the function header below.

function [ ZeroList ] = TestIfZeroList( L )


%Input: L is a list of numbers of any length greater than 1.
%Output: ZeroList will be 1 if L contains only zeros and 0 otherwise.
squared L L
if sunksquared O
Zerolist 0
else
Kist
end
qEnd
3. (5 points) What is the output to the following function call, for the (incorrect) function BisectionMethod below? Note
that by default MATLAB’s sin function works in radians, not degrees.
>> [xllist, xulist] = BisectionMethod(@(x)sin(x), 3, 3)

function [ xllist, xulist] = BisectionMethod ( f, xl, xu)


3 3
xllist = 1:0.5:2;
Xl list I 1.5 z
xulist = 1:2;
for i = 1:2 xulist112
II
xr = (xu+xl)/2; Xr xr 3 3
if f(xl)*f(xr) < 0
xu = xr; false false
elseif f(xl)*f(xr) > 0

else
xl = xr;
I
output
xu = xr;
xl = xr;
end
xulist(i) = xu; Xulist
3 2 Xul 3 3
tI
xllist(i) = xl;
end
end xllist 31.5 23 1 3

Potrebbero piacerti anche