CS 1112 Exercise 5

Due date: Sunday, March 21, 11:00pm EST.

The exercise must be submitted on Matlab Grader.

Problem 1

Implement the following function so that it performs as specified:

function [s,c] = trig(a)
% s and c are the sine and cosine of angle a.
% a is the measure of an angle in degrees, assumed non-negative.

Write a function showTrig() that makes effective use of trig to print a table of sine and cosine values for 0°, 2°, 4°, …, 30°. Function showTrig() takes no arguments and does not return any value (but it has the side effect of printing to the Command Window).

Problem 2

The following function produces a pretty good estimate of sin(x) if |x| ≤ 2π:

function y = mySin0(x)
% y is an approximation of sin(x) where x is a radian measure
y= x;
for k = 1:8
    y= y + (-1)^k * x^(1 + 2*k) / factorial(1 + 2*k);
end

It is horrible if |x| is large. Using the fact that the sine function is periodic, write a function mySin1(x) that produces a good sine approximation for any non-negative x. Make effective use of mySin0().

Problem 3

Consider the binomial coefficient (nk)=n!k!(nk)!{n \choose k} = \frac{n!}{k!(n-k)!} We will call this value “n-choose-k”. Implement the following function so that it performs as specified:

function d = digitsOfBinCoef(n,k)
% d is the number of digits required to write the binomial coefficient n-choose-k
% n and k are both non-negative integers, n<=100, and n>=k.

Recall that if x houses a positive integer, then the value of floor(log10(x))+1 is the number of base-10 digits that are required to write the value of x. Make use of built-in function factorial().

Problem 4

Last week, you wrote a script to produce ten lines of output: the nth line, where n=1, …, 10, displays the number of digits required to write down each of the binomial coefficients (n1),(n2),,(nn){n \choose 1}, {n \choose 2}, \ldots, {n \choose n} Write a function showDigitsOfBinCoefs() to solve this problem again, but now make use of function digitsOfBinCoef() from above. Function showDigitsOfBinCoefs() takes no arguments and does not return any value.

Problem 5

Implement the following function so that it performs as specified:

function s = mySum(v)
% s is the sum of all the values in numeric vector v.
% v may be empty, in which case the sum is zero.
% The only built-in function allowed is length().

Problem 6

Implement the following function so that it performs as specified:

function val = myMax(v)
% val is the largest value in numeric vector v.
% v is not empty. The only built-in function allowed is length().