Math 111: MATLAB Assignment 1

DUE DATE:  FEBRUARY 4, 2011

 

 

In this assignment, we will be investigating the behavior of secant lines connecting points of curves. As the points being connected get closer together, these lines approach the tangent line to the curve at a point.

Here are some links to general information to help you get started in MATLAB. To begin, click on the Matlab icon on your desktop to open a Matlab screen. Click on File -> New -> m-file to create a new file. 

You can find more information to help you get started with MATLAB at Matlab Documentation.

 

 

Your Assignment

 

 

In this assignment, we use MATLAB to investigate how secant lines over shorter intervals approach the tangent line to a curve.

The sample code given below considers the function y=x^3 and investigates the slope of the curve at (1,y(1)).

The first figure considers secant lines connecting (1,y(1)) to points to the right -- (3,y(3)), (2,y(2)) and (1.5,y(1.5)) respectively

The second figure considers secant lines connecting points (1-h,y(1-h)) to (1+h,y(1+h)) where h=2,1 and 0.5 respectively.

The tangent line through (1,y(1)) is also shown. There are lots of comments in the code so you should try to read through it step by step.

  1. Run the given code and comment on whether one method or the other (i.e. using the point (1,y(1)) and points to the right is the first method and using points with (1,y(1)) in the middle is the second method) or both give slopes approaching the true slope of the tangent line. Is one method better than the other for this function?

  2. Revise the code to consider similarly secant and tangent lines for the function y = 16/x at (4,y(4)). Plot over the interval 2<x<6 and make tables. (Two figures and two tables).

  3. Revise the code to consider similarly secant and tangent lines for the function y = x^2 -2x + 1 at (1,y(1)). Plot over the interval -1<x<3 and make tables. (Two figures and two tables)

For each of the steps 1, 2 and 3, use the same values of h (2, 1, and 0.5) as provided in the the code below.

Label the plots with your name in addition to the curve (y=x^3, y=16/x and y=x^2-2x+1) for each case.

 

Ä Do you notice anything unusual (interesting) with the result for slopes in these cases?

 

Matlab note: The '*' sign will not, however, multiply two arrays together. If we want to multiply two arrays together, or divide by an array we need to use the matlab commands '.*' and './' rather than '*' or '/'. Similarly, to raise an array to a power, we need to use the '.^' command. Finally, use the matlab command 'sqrt(x)' to take the square root of x.

 

Either of the following MATLAB codes may be used as the basis for your work.

The first version is easier to follow but requires more revision.

The second is harder to follow but requires much less revision.

You need not hand in your codes -- just the plots and answers to the questions.

 

 

FIRST CODE:

 

%The following program shows how to plot curves, and secant and tangent

%lines.

 

%In this file, in figure 1 we plot the curve y=x^3 and the secant lines:

%   through (1,y(1)) and (3,y(3))

%   through (1,y(1)) and (2,y(2))

%   through (1,y(1)) and (1.5,y(1.5)) and

%   the tangent line through (1,y(1))

 

% For figure 2 we consider secant lines connecting:

%   through (-1,y(-1)) and (3,y(3))

%   through (0,y(0)) and (2,y(2))

%   through (0.5,y(0.5)) and (1.5,y(1.5)) and

%   the tangent line through (1,y(1))

 

%Helpful tip - The best way to learn MATLAB is to use the help menu.  Hit

%F1 to start up help. Each command can be explained in there.
 

x = -5:0.01:5;      %This command makes a vector from -5 to 5 with

                    %increments of 0.01.  The semi-colon suppresses

                    %the output of this command from showing up in the

                    %command window. You can see what each command is

                    %doing if you remove the semi-colon from that line

 

y = x.^3;           %This command defines the function y = x^3.  The '.'

                    %gives the command to square each element of the

                    %vector x.

 

figure(1);

plot(x,y,'black','LineWidth',2);     %Plot the function.

hold on;                             %Wait for more commands. Don't erase plot

grid on;                             %Display the grid.

 

F = @(x) x.^3;                       %Create a function f(x)=x^3

 

%Plot the secant line connecting (1,f(1)) and (3,f(3)) y = m(x - x1) + y1.

Y2 = F(3);

Y1 = F(1);

X2=3;

X1=1;

slope1 = (Y2-Y1) / (X2-X1);

plot(x,(slope1 * ( x - X1) + Y1),'red','LineWidth',1);

        %This is the secant line that connects

        %(1,f(1)) and (3,f(3)) y = m(x - x1) + y1.

 

 

%Plot the secant line connecting (1,f(1)) and (2,f(2)) y = m(x - x1) + y1.

Y2 = F(2);

Y1 = F(1);

X2=2;

X1=1;

slope2 = (Y2-Y1) / (X2-X1);

plot(x,(slope2 * ( x - X1) + Y1),'blue','LineWidth',1);

        %This is the secant line that connects

        %(1,f(1)) and (2,f(2)) y = m(x - x1) + y1.

 

 

%Plot the secant line connecting (1,f(1)) and (1.5,f(1.5)) y = m(x - x1) + y1.

Y2 = F(1.5);

Y1 = F(1);

X2=1.5;

X1=1;

slope3 = (Y2-Y1) / (X2-X1);

plot(x,(slope3 * ( x - X1) + Y1),'green','LineWidth',1)

        %This is the secant line that connects

        %(1,f(1)) and (1.5,f(1.5)) y = m(x - x1) + y1.

 

 

%Plot the tangent line through (1,f(1))       

dfdx = @(x) 3 * x.^2; % define the derivative df/dx = 3x^2

Trueslope = dfdx(1);

plot(x,(Trueslope * ( x - X1) + Y1),'magenta','LineWidth',2)

        %This is the tangent line through (1,f(1))

 

 

plot(X1,Y1,'ok','MarkerFaceColor','black','MarkerSize',5); %Mark the point (1,f(1))

title('y = x^3','Fontsize',16);      %Display the title y = x^3.

xlabel('x','Fontsize',14);           %Display label for x-axis.

ylabel('y','Fontsize',14);           %Display label for y-axis.

xlim([-1 3]);                        %Zoom to region from x = -1 to x = 3.

hold off;

 

 

% print a table with h and slope

fprintf(' h      slope   \n')

fprintf('---  -----------\n')

fprintf('  %1i %12.8f\n',2,slope1)

fprintf('  %1i %12.8f\n',1,slope2)

fprintf('%2.1f %12.8f\n',0.5,slope3)

fprintf('  %1i %12.8f\n',0,Trueslope)

 

 

% Repeat with a centered slope calculation, i.e.

%   slope = [f(x+h) - f(x-h)]/[2h]

figure(2);

plot(x,y,'black','LineWidth',2);     %Plot the function.

hold on;                        %Wait for more commands.

grid on;                             %Display the grid.

 

 

%Plot the secant line connecting (-1,f(-1)) and (3,f(3)) y = m(x - x1) + y1.

Y2 = F(3);

Y1 = F(-1);

X2=3;

X1=-1;

slope1 = (Y2-Y1) / (X2-X1);

plot(x,(slope1 * ( x - X1) + Y1),'red','LineWidth',1);

        %This is the secant line that connects

        %(-1,f(-1)) and (3,f(3)) y = y = y = m(x - x1) + y1.

 

 

%Plot the secant line connecting (0,f(0)) and (2,f(2)) y = m(x - x1) + y1.

Y2 = F(2);

Y1 = F(0);

X2=2;

X1=0;

slope2 = (Y2-Y1) / (X2-X1);

plot(x,(slope2 * ( x - X1) + Y1),'blue','LineWidth',1);

        %This is the secant line that connects

        %(0,f(0)) and (2,f(2)) y = m(x - x1) + y1.

 

 

%Plot the secant line connecting (0.5,f(0.5)) and (1.5,f(1.5)) y = m(x - x1) + y1.

Y2 = F(1.5);

Y1 = F(0.5);

X2=1.5;

X1=0.5;

slope3 = (Y2-Y1) / (X2-X1);

plot(x,(slope3 * ( x - X1) + Y1),'green','LineWidth',1)

        %This is the secant line that connects

        %(0.5,f(0.5)) and (1.5,f(1.5)) y = m(x - x1) + y1.

 

 

%Plot the tangent line through (1,f(1))       

plot(x,(Trueslope * ( x - 1) + F(1)),'magenta','LineWidth',2)

        %This is the tangent line through (1,f(1))

 

 

plot(1,F(1),'ok','MarkerFaceColor','black','MarkerSize',5); %Mark the point (1,f(1))

title('y = x^3','Fontsize',16);      %Display the title y = x^3.

xlabel('x','Fontsize',14);           %Display label for x-axis.

ylabel('y','Fontsize',14);           %Display label for y-axis.

xlim([-1 3]);                         %Zoom to region from x = -1 to x = 3.

hold off;

 

 

% print a table with h and slope

fprintf('\nCentered Difference \n')

fprintf(' h      slope   \n')

fprintf('---  -----------\n')

fprintf('  %1i %12.8f\n',2,slope1)

fprintf('  %1i %12.8f\n',1,slope2)

fprintf('%2.1f %12.8f\n',0.5,slope3)

fprintf('  %1i %12.8f\n',0,Trueslope)

 

 =============================================END OF FIRST CODE=============================

 

 

SECOND CODE

function Assigment1()

%IMPORTANT NOTE

%The name of the function FILENAME should be changed to match the name

%of the M-file you are storing this as. E.g. If you named this file

%"george.m", the first line should read "function george()".

%

%The following program shows how to plot curves, and secant and tangent

%lines.

%In this file, in figure 1 we plot the curve y=x^3 and the secant lines:

%   through (1,y(1)) and (3,y(3))

%   through (1,y(1)) and (2,y(2))

%   through (1,y(1)) and (1.5,y(1.5)) and

%   the tangent line through (1,y(1))

 

 

% For figure 2 we consider secant lines connecting:

%   through (-1,y(-1)) and (3,y(3))

%   through (0,y(0)) and (2,y(2))

%   through (0.5,y(0.5)) and (1.5,y(1.5)) and

%   the tangent line through (1,y(1))

 

 

 

%Helpful tip - The best way to learn MATLAB is to use the help menu.  Hit

%F1 to start up help.  Each command can be explained in there.

 

 

%------- VALUES YOU WILL NEED TO CHANGE TO COMPLETE YOUR ASSIGNMENT ------

F = @(x) x.^3;         %This command defines the function y = x^3.  The '.'

                                %gives the command to square each element of the

                                %vector x. You will also need the '.' for

                                %multiplication and division, e.g. (x+1)./(x-1). You do

                                %NOT need a '.' for addition or subtraction.

                   

dFdx = @(x) 3*x.^2;       %This defines the derivative dF/dx = 3x^2. Note that

                                        %constant mulitiplication does not require the '.'.

                                        %You will need to work out the derivatives of the given

                                        %functions by hand and then input them here.

                   

a = 1;           %This is the value at which we will be finding the

                    %tangent line to the function F.                

 

GraphTitle = 'y = x^3';     %This title will be displayed at the top of

                                        %your figures.

                       

XLimits = [-1 3];               %These values are the [left right] side of what will

                                         %be displayed in your figure

 

 

%-------- ONLY THESE VALUES WILL NEED TO BE CHANGED ----------------------

 

x = XLimits(1):0.01:XLimits(2);      %This command makes a vector of

                    %x-values that will span the plotting region from left

                    %to right in increments of 0.01.  The semi-colon

                    %suppresses the output of this command from showing up

                    %in the command window. You can see what each command

                    %is doing if you remove the semi-colon from that line

 

y = F(x);       %We will use these y-values to plot the function.          

 

 

% BEGIN PLOTTING THE FIRST FIGURE

figure(1);                                       %Open a new graph

plot(x,y,'black','LineWidth',2);       %Plot the function.

hold on;                                        %Wait for more commands. Don't erase plot

grid on;                                         %Display the grid.

 

 

% For h=2, plot the secant line connecting (a,f(a)) and (a+2,f(a+2))

secant1 = getSecant(F,a,2);

                            %This function is defined near the end of the

                            %file. (You should take a look.) It returns a

                            %representation of the secant line y=mx+b as a

                            %vector [m,b]

plot(x,polyval(secant1,x),'red','LineWidth',1);

                            %The plot function plots

                            %pairs of (x,y) values. In this case, the

                            %x-values are the ones we defined from [-5,5]..

                            %The y-values come from evaluating the secant

                            %line at the corresponding x-values. polyval is

                            %simply a convenient way to evaluate

                            %polynomials (including lines) in Matlab.

 

% Similarly for h=11

secant2 = getSecant(F,a,1);

plot(x,polyval(secant2,x),'blue','LineWidth',1);

 

% and for h=0.55

secant3 = getSecant(F,a,0.5);

plot(x,polyval(secant3,x),'green','LineWidth',1); 

 

% Plot the tangent line through (a,f(a))

TrueSlope = dFdx(a);        %This is the actual slope of the tangent line.

                                         %What would happen if you tried to use

                                         %getSecant(F,a,0) instead?

                           

Intercept = F(a)-TrueSlope*a;

                                        %The intercept comes from

                                        %y = m(x-a)+F(a) = mx + (F(a)-ma)

 

plot(x,polyval([TrueSlope,Intercept],x),'magenta','LineWidth',2);

                                        %This is the tangent line through (a,F(a))

 

% Now we will make the graph look a little nicer.

plot(a,F(a),'ok','MarkerFaceColor','black','MarkerSize',5);

                            %Mark the point (a,F(a))

title(GraphTitle,'Fontsize',16);      %Display the title y = x^3.

xlabel('x','Fontsize',14);               %Display label for x-axis.

ylabel('y','Fontsize',14);               %Display label for y-axis.

xlim(XLimits);                             %Zoom to region from x = -1 to x = 3.

 

hold off;                                       %We are done adding to this figure.

 

% Print a table with h and the corresponding slope

fprintf(' h      slope   \n')

fprintf('---  -----------\n')

fprintf('  %1i %12.8f\n',2,secant1(1))

fprintf('  %1i %12.8f\n',1,secant2(1))

fprintf('%2.1f %12.8f\n',0.5,secant3(1))

fprintf('  %1i %12.8f\n',0,TrueSlope)

 

% BEGIN PLOTTING THE SECOND FIGURE

% This repeats the previous example with a centered slope calculation, i.e.

% slope = [f(x+h) - f(x-h)]/[2h]

 

figure(2);                                       %Open the second graph

plot(x,y,'black','LineWidth',2);       %Plot the function.

hold on;                                         %Wait for more commands. Don't erase plot

grid on;                                          %Display the grid.

 

% For h=2, plot the secant line connecting (a-2,f(a-2)) and (a+2,f(a+2))

secant1 = getCenteredSecant(F,a,2);

                            %This function is also defined near the

                            %end of the file. (You should also take a

                            %look.) It also returns a representation of the

                            %secant line y=mx+b as a vector [m,b]

 

plot(x,polyval(secant1,x),'red','LineWidth',1);

 

% Similarly for h=11

secant2 = getCenteredSecant(F,a,1);

plot(x,polyval(secant2,x),'blue','LineWidth',1);

 

% and for h=0.55

secant3 = getCenteredSecant(F,a,0.5);

plot(x,polyval(secant3,x),'green','LineWidth',1); 

 

% Plot the tangent line through (a,f(a))

plot(x,polyval([TrueSlope,Intercept],x),'magenta','LineWidth',2);

                            %This is the tangent line through (a,F(a))

 

% Again we will make the graph look a little nicer.

plot(a,F(a),'ok','MarkerFaceColor','black','MarkerSize',5);

                            %Mark the point (a,F(a))

title(GraphTitle,'Fontsize',16);      %Display the title y = x^3.

xlabel('x','Fontsize',14);           %Display label for x-axis.

ylabel('y','Fontsize',14);           %Display label for y-axis.

xlim(XLimits);                        %Zoom to region from x = -1 to x = 3.

 

hold off;                   %We are done adding to this figure..

 

% Print a table with h and the corresponding slope

fprintf(' h      slope   \n')

fprintf('---  -----------\n')

fprintf('  %1i %12.8f\n',2,secant1(1))

fprintf('  %1i %12.8f\n',1,secant2(1))

fprintf('%2.1f %12.8f\n',0.5,secant3(1))

fprintf('  %1i %12.8f\n',0,TrueSlope)

end

 

% getSecant creates a polynomial representing the secant line to the graph

% i.e. a line connecting (a,f(a)) and (a+h,f(a+h))

% in Matlab, the line y=mx+b is represented by the vector [m,b]

function secant = getSecant(f,a,h)

    y2 = f(a+h);

    y1 = f(a);

 

    secant(1) = (y2-y1) / h; % slope

    secant(2) = y1-secant(1)*a; % intercept = slope*a + y1 comes from the formula y=m(x-x1)+y1

end

 

 

% getCenteredSecant creates a polynomial representing the secant line to the graph

% i.e. a line connecting (a-h,f(a-h)) and (a+h,f(a+h))

% in Matlab, the line y=mx+b is represented by the vector [m,b]

function secant = getCenteredSecant(f,a,h)

secant = getSecant(f,a-h,2*h);

                                   %This allows us to reuse code. We can do

                                   %this because a-h + 2h = a+h.

end

===========================================END OF SECOND CODE=========================

 

Last update: 01/20/2011