%%% Purpose: function written for Catalyst 2015
%%% Date: August 2015
%%% Written by: Alexandria Volkening
%%% Description: This code calculates the average rate of change of a
%%% function f(x) with respect to x over an interval from x = a to
%%% x = a + h. As h gets closer and closer to zero, the average rate of
%%% change approaches the instantaneous rate of change, or derivative, of
%%% f(x) at a.
%%%
%%% Instructions:
%%% Step 1: Use the code below to calculute the average rate of
%%% change of f(x) = x^2 for h = 2, 1, 0.5 0.1, 0.01, and 0.001 at a = 3.
%%% Step 2: Repeat Step 1 for a = 0.
%%% Step 3: Use the code below to calculute the average rate of
%%% change of f(x) = x^3 for h = 2, 1, 0.5 0.1, 0.01, and 0.001 at a = 3.
%%% Step 4: Repeat Step 1 for a new function f(x) and point a of your
%%% choice.
function [] = ApproximateDerivative()
%%% First we define the step size h and value a at which we want to
%%% approximate the rate of change.
h = 2;
a = 3;
%%% Next we define the function f(x). It is important to always include a
%%% period before ^ (exponent), * (multiplication), or / (division) in Matlab.
%%% For example, the function g = 5*x would be written in Matlab as
%%% g = @(x) 5.*x.
f = @(x) x.^2;
%%% Now we calculate the average rate of change of f(x) in the interval
%%% from x = a to x = a + h.
rateOfChange = (f(a + h) - f(a))/h;
%%% The remainder of the code displays results and does not need to be
%%% altered as part of the homework assignment.
%%% We print the result to the main Matlab window.
disp(['The average rate of change of ' func2str(f) ' in the interval x = ' ...
num2str(a) ' to x = ' num2str(a) ' + ' num2str(h) ' is ' num2str(rateOfChange) '.'])
%%% We also display a graph of f(x) and the secant line from x = a to
%%% x = a + h. The slope of the secant line is the average rate of change
%%% in that interval. As the interval becomes shorter, it approaches the
%%% slope of the tangent line at x = a, or the derivative f'(a).
xpoints = -a - h - 3:.001:a + h + 3;
figure
plot(xpoints, f(xpoints), 'k', 'LineWidth', 1)
hold on
plot(xpoints, rateOfChange*(xpoints - a) + f(a), 'g', 'LineWidth', 1.5)
axis([min(xpoints) max(xpoints) min(f(xpoints))-1 max(f(xpoints))])
legend('f(x)', 'secant line')
title(['Plot of f(x) and the secant line from x = ' num2str(a) ' to ' ...
num2str(a+h)]);
xlabel('x')
ylabel('y')
hold off
end