Engineering 7:
Prof. Alexandre Bayen
Introduction to Programming for Engineers
Spring 2011
Lab 10: Numerical Differentiation and Integration
Date Assigned: 5:00pm, Friday – April 15.
Date Due: 5:00pm, Friday – April 22.
Problem 1
: Write a function with header
[dy, X] = myNumDiff(f, a, b, n, option)
where
f
is handle to
a function. The function
myNumDiff
should compute the derivative of
f
numerical for
n
evenly spaced points
starting at
a
and ending at
b
according to the method defined by
option
. The input argument
option
is one of
the following strings:
‘forward’
, ‘
backward’
,
‘central’
. Note that for the forward and backward method, the
output argument,
dy
, should be
1x(n-1)
, and for the central difference method
dy
should be
1x(n-2).
The
function should also output a row vector
X
that is the same size as
dy
and denotes the x-values for which
dy
is
valid.
Test Cases:
>> x = linspace(0, 2*pi,100);
>> f = @sin;
>> [dyf, Xf] = myNumDiff(f, 0, 2*pi, 10, 'forward');
>> [dyb, Xb] = myNumDiff(f, 0, 2*pi, 10, 'backward');
>> [dyc, Xc] = myNumDiff(f, 0, 2*pi, 10, 'central');
>> plot(x, cos(x), Xf, dyf, Xb, dyb, Xc, dyc)
>> title('Analytic and Numerical Derivatives of Sine')
>> xlabel('x')
>> ylabel('y')
>> grid on
>> legend('analytic', 'forward', 'backward', 'central')
0
1
2
3
4
5
6
7
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Analytic and Numerical Derivatives of Sine
x
y
analytic
forward
backward
central