This preview shows pages 1–3. Sign up to view the full content.
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(n1)
, and for the central difference method
dy
should be
1x(n2).
The
function should also output a row vector
X
that is the same size as
dy
and denotes the xvalues 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
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentEngineering 7:
Prof. Alexandre Bayen
Introduction to Programming for Engineers
Spring 2011
>> x = linspace(0, pi, 1000);
>> f = @(x) sin(exp(x));
>> [dy10, X10] = myNumDiff(f, 0, pi, 10, 'central');
>> [dy20, X20] = myNumDiff(f, 0, pi, 20, 'central');
>> [dy100, X100] = myNumDiff(f, 0, pi, 100, 'central');
>> plot(x, cos(exp(x)).*exp(x), X10, dy10, X20, dy20, X100, dy100)
>> xlabel('x')
>> ylabel('y')
>> title('Numerical Derivative of f(x) = sin(e^{x})')
>> legend('Analytic', '10 points', '20 points', '100 points')
0
0.5
1
1.5
2
2.5
3
3.5
25
20
15
10
5
0
5
10
15
20
x
y
Numerical Derivative of f(x) = sin(e
x
)
Analytic
10 points
20 points
100 points
This is the end of the preview. Sign up
to
access the rest of the document.
 Spring '08
 HOROWITZ

Click to edit the document details