MATLAB Examples - Numerical Integration
MATLAB Examples - Numerical Integration
Examples
Numerical Integration
Hans-Petter Halvorsen
Integration
'
% 𝑓 𝑥 𝑑𝑥
(
Integration
Given the function:
𝑦 = 𝑥+
A = 0.3350
Students: Try this example
Example: Numerical Integration
We know that the exact solution is:
In MATLAB we have several built-in functions we can use for numerical integration:
clear
clc
close all
x=0:0.1:1;
y=x.^2;
plot(x,y)
𝑦 = 𝑥 - + 2𝑥 + − 𝑥 + 3
𝑎 = −1 and 𝑏 = 1 gives:
1 2 1 22
𝐼 = 1−1 + 1+1 − 1−1 +3 1+1 =
4 3 2 3
Symbolic Math Toolbox
We start by finding the Integral using the Symbolic Math Toolbox:
clear, clc
syms f(x)
syms x
I = int(f)
http://se.mathworks.com/help/symbolic/getting-started-with-symbolic-math-toolbox.html
Symbolic Math Toolbox
The Integral from a to b:
clear, clc
syms f(x)
syms x
f(x) = x^3 + 2*x^2 -x +3
a = -1;
b = 1;
Iab = int(f, a, b)
http://se.mathworks.com/help/symbolic/getting-started-with-symbolic-math-toolbox.html
clear, clc
x = -1:0.1:1;
y = myfunc(x);
plot(x,y)
% Exact Solution
a = -1;
b = 1;
Iab = 1/4*(b^4-a^4 )+2/3*(b^3-a^3 )-
1/2*(b^2-a^2 )+3*(b-a)
% Method 1
avg_y = y(1:length(x)-1) + diff(y)/2;
A1 = sum(diff(x).*avg_y)
MATLAB gives the following results:
% Method 2
A2 = quad(@myfunc, -1,1) Iab = 7.3333
A1 = 7.3400
% Method 3 A2 = 7.3333
A3 = quadl(@myfunc, -1,1)
A3 = 7.3333
Integration on Polynomials
Given the following equation:
𝑦 = 𝑥 - + 2𝑥 + − 𝑥 + 3
'
' : - +
- +
𝑥 2𝑥 𝑥
% (𝑥 + 2𝑥 − 𝑥 + 3)𝑑𝑥 = + − + 3𝑥 <
( 4 3 2
(
E-mail: [email protected]
Blog: http://home.hit.no/~hansha/