Skip to main content

Section 5.3 Examples and questions

These are additional examples for reviewing the topic we have covered. When reading each example, try to find your own solution before clicking “Answer”. There are also questions for reviewing the concepts of this section.

Define an anonymous function meansin = @(n) ... which computes the mean value of \(\sin(1)\text{,}\) \(\sin(2)\text{,}\) ..., \(\sin(n)\text{.}\) Use it to display the values meansin(n) for n equal to 10, 50, 250, 1870, and 5000. What pattern do you observe?

Answer
meansin = @(n) mean(sin(1:n));

for n = [10 50 250 1870 5000]
    disp(meansin(n))
end

Explanation: this is a reminder that the vector in for loop does not have to be of the form a:b even though this form is most common. Here the use of a loop avoids having to write

disp(meansin(10))
disp(meansin(50)) 
disp(meansin(250)) 

and so on.

It appears that the mean values approach 0 as n grows. This can be proved mathematically: see the homework section.

Define a named function function y = p(x, a, n) which computes the polynomial

\begin{equation*} p(x, a, n) = 1 + \frac{x}{a} + \frac{x^2}{a + 1} + \frac{x^3}{a+2} + \cdots + \frac{x^n}{a+n-1} \end{equation*}

Assume that x may be a vector, a is a real number, and n is a positive integer (the degree of our polynomial).

Answer
function y = p(x, a, n)
    y = ones(size(x));
    for k = 1:n
        y = y + x.^k/(a+k-1);
    end
end

The command size(x) returns the size of \(x\) as the number of rows and columns. Consequently, ones(size(x)) means creating a vector or matrix of the same size as x, but with all entries 1. If we started with y = 1 instead, the computation would still work because adding 1 to a vector like x.^k means adding 1 to each component of the vector (ex. However, when n = 0 the loop does not run at all and the output would be a scalar 1 instead of a vector, which is a bug.

Use the function from Example 5.3.2 to plot the polynomial with \(a = -3/2\) and \(n = 6\) on the interval \([-1, 1]\text{.}\)

Answer
x = linspace(-1, 1, 500);
plot(x, p(x, -3/2, 6))

function y = p(x, a, n)
    y = ones(size(x));
    for k = 1:n
        y = y + x.^k/(a+k-1);
    end
end

What does the function f defined by f = @(x, y) [x y] do? Can one give it vector inputs x, y? If so, does it matter if they are row vectors or column vectors? Do they need to be of the same size?