๐ Lecture 20 โ Euler Method on MATLAB
๐ Overview: This lecture demonstrates how to implement the Euler method numerically in MATLAB to solve ordinary differential equations. It also shows how to compare the numerical approximation with the exact analytical solution using MATLAB's symbolic computation capabilities.
๐๏ธ Topics Covered
The lecture covers MATLAB implementation of the Euler method for solving ODEs, including function definitions, for-loop iterations for numerical approximation, memory allocation, plotting numerical solutions, and solving the same ODE symbolically using dsolve to compare with the exact solution.
๐ Lecture Summary
Euler Method on MATLAB
The lecture demonstrates implementing the Euler method in MATLAB to approximate the solution of the differential equation dy/dx = x/y with initial condition y(0)=1 over the interval [0,2]. The numerical solution is then compared with the exact analytical solution.
The MATLAB code begins by defining the function handle for the differential equation: f=@(x,y)(x/y). The interval boundaries are set with a=0 and b=2, with the initial value ya=1. The number of steps is n=10, and the step size h is calculated as (b-a)/n.
Memory allocation is performed using y=zeros(n+1,1) to create a zero column vector for efficiency. The initial condition is stored as y(1)=ya. The Euler formula is implemented in a for-loop: y(j+1)=y(j)+h*f(x(j),y(j)), with x values updated as x(i+1)=x(i)+h.
The numerical solution is plotted using plot(x,y,'-b') with a blue line. The hold on command keeps the current plot to overlay the exact solution.
๐ Definition โ Euler's formula: y(j+1) = y(j) + h * f(x(j), y(j)) โ approximates the next y value using the current y value plus the step size multiplied by the slope at the current point
๐ Formula: h = (b-a)/n โ step size equals the interval length divided by the number of steps
๐ Example: For dy/dx = x/y with y(0)=1, n=10 steps over [0,2]: h = (2-0)/10 = 0.2, the first approximation would be y(1) = 1 + 0.2 ร (0/1) = 1, and subsequent steps continue using Euler's formula
Symbolic Solution and Comparison
After the numerical approximation, the code solves the same ODE symbolically using MATLAB's symbolic toolbox. The symbolic variable is defined with syms y(x). The ODE is defined as ode= diff(y,x)== x/y with the condition cond=y(0)==1.
The dsolve function solves the ODE symbolically: S=dsolve(ode,cond). The symbolic solution is converted to a function handle using F=matlabFunction(S) for plotting.
The exact solution is plotted using fplot(F,[0,2],'r',"LineWidth",2) with a red line and line width of 2. The hold off command releases the hold on the current figure.
๐ก Why this matters: This comparison shows the accuracy of the numerical Euler method against the true analytical solution, helping visualize the approximation error that accumulates with the Euler method.
๐ Definition โ dsolve: MATLAB's symbolic differential equation solver that returns the exact analytical solution when possible
๐ Example: For dy/dx = x/y with y(0)=1, dsolve returns the exact solution, which is then plotted as a red line to compare with the blue numerical approximation from Euler's method
โญ Key Takeaways
The Euler method provides a straightforward numerical approach to approximate solutions of ordinary differential equations when analytical solutions are difficult or impossible to obtain. MATLAB implementation requires careful memory allocation with zeros, proper for-loop indexing, and step size calculation. Comparing numerical and exact solutions through overlay plotting reveals the approximation error inherent in the Euler method. The symbolic toolbox in MATLAB provides a powerful way to verify numerical results when analytical solutions exist. Understanding both numerical and symbolic approaches gives engineers and scientists flexibility in solving differential equations.
๐ง Quick Revision Questions
- What is the formula for the step size h in the Euler method given interval [a,b] and n steps?
- How is the Euler formula implemented in MATLAB's for-loop for approximating y(j+1)?
- Why is memory allocation using zeros(n+1,1) important in MATLAB?
- What MATLAB function solves an ODE symbolically, and what syntax defines the ODE and initial condition?
- How do you overlay the numerical and exact solutions on the same plot?
๐ Lecture 21 โ Numerical Integration
๐ Overview: This lecture introduces numerical methods for approximating definite integrals when analytic evaluation is difficult or impossible. The focus is on the Trapezoidal Rule, including its derivation, implementation via MATLAB code, and practical application with a worked example.
๐๏ธ Topics Covered
The lecture covers the motivation for numerical integration, the mathematical formulation of the Trapezoidal Rule, a step-by-step MATLAB implementation, and a numerical example demonstrating integration of f(x)=1/(1+x) from 1 to 2 with 10 subintervals.
๐ Lecture Summary
Numerical Integration
Sometimes, the evaluation of expressions involving integrals can become daunting, if not indeterminate. For this reason, a wide variety of numerical methods has been developed to simplify the integral. These methods approximate the value of a definite integral using discrete data points rather than analytic antiderivatives.
Trapezoidal Rule
The Trapezoidal Rule is a numerical integration technique that approximates the area under a curve by dividing the interval into n subintervals of equal width and approximating the function on each subinterval as a straight line segment (trapezoid). The total area is the sum of the areas of these trapezoids.
๐ Definition โ Trapezoidal Rule: A numerical method that approximates the definite integral โซโแต f(x)dx by dividing [a,b] into n equal subintervals of width h = (bโa)/n and summing the areas of trapezoids formed under the curve.
๐ Formula: โซโแต f(x)dx โ (h/2)[f(a) + f(b) + 2โ_{k=1}^{n-1} f(a + kh)] โ h is the subinterval width, f(a) and f(b) are endpoints, and the sum includes all interior points each multiplied by 2.
๐ก Why this matters: The Trapezoidal Rule is a foundational method that balances simplicity with reasonable accuracy. Increasing n (more subintervals) improves accuracy but adds computational cost. It is a building block for advanced methods like Simpson's Rule.
MATLAB Code Implementation
The lecture provides a complete MATLAB code for implementing the Trapezoidal Rule. The code defines the function, takes user inputs for limits and number of subintervals, computes the sum of interior points in a loop, and applies the formula to output the approximated integral.
Code:
clc;
clear all;
f=@(x)1/(1+x); % Change here for different function
a=input('Enter lower limit a: '); % example a=1
b=input('Enter upper limit b: '); % example b=2
n=input('Enter the no. of subinterval: '); % example n=10
h=(b-a)/n;
sum=0;
for k=1:1:n-1
x(k)=a+k*h;
y(k)=f(x(k));
sum=sum+y(k);
end
% Formula: (h/2)*[(y0+yn)+2*(y2+y3+..+yn-1)]
answer=h/2*(f(a)+f(b)+2*sum);
fprintf('\n The value of integration is %f',answer); % example: The value of integration is 0.410451
๐ Example: Use the Trapezoidal Rule to approximate โซโยฒ 1/(1+x) dx with n=10 subintervals.
- a = 1, b = 2, n = 10
- h = (2โ1)/10 = 0.1
- f(a) = f(1) = 1/(1+1) = 0.5
- f(b) = f(2) = 1/(1+2) = 0.3333
- Interior points at x = 1.1, 1.2, ..., 1.9 โ compute f(x) for each
- Sum of interior f(x) values = 4.2940 (approximate)
- Answer = (0.1/2) ร [0.5 + 0.3333 + 2(4.2940)] = 0.05 ร [0.8333 + 8.588] = 0.05 ร 9.4213 = 0.410451
โญ Key Takeaways
The Trapezoidal Rule is a simple yet powerful numerical method for approximating definite integrals when analytic solutions are impractical. Its formula uses the average of endpoint contributions plus twice the sum of all interior points, scaled by half the subinterval width. The MATLAB implementation shows how to code this method generically, allowing easy modification for different functions, limits, and precision levels. Accuracy increases with the number of subintervals n, but so does computational effort, creating a trade-off. This method is the foundation for understanding more advanced numerical integration techniques.
๐ง Quick Revision Questions
- What is the formula for the Trapezoidal Rule, and what does each term represent?
- In the MATLAB code, what does the loop
for k=1:1:n-1compute, and why does it start at 1 and end at n-1? - How does increasing the number of subintervals n affect the accuracy of the Trapezoidal Rule approximation?
- For the example โซโยฒ 1/(1+x) dx with n=10, calculate h and identify f(a) and f(b).
- How would you modify the MATLAB code to integrate a different function, say f(x)=xยฒ, from 0 to 1 with 5 subintervals?
๐ Lecture 22 โ Simpsonโs 1/3 Rule
๐ Overview: This lecture introduces Simpsonโs 1/3 Rule, a numerical integration method that approximates the definite integral of a function by fitting a second-degree polynomial (parabola) over each pair of sub-intervals. It explains the formula, the requirement for an even number of sub-intervals, and provides a complete MATLAB implementation for practical computation.
๐๏ธ Topics Covered
The lecture covers the derivation and formula of Simpsonโs 1/3 Rule, the requirement that the number of sub-intervals n must be even, the separation of function evaluations into odd and even terms, and a complete MATLAB program implementing the rule with user-defined input for the function, limits, and number of sub-intervals.
๐ Lecture Summary
Simpsonโs 1/3 Rule โ Formula
Simpsonโs 1/3 Rule approximates the integral of a function by dividing the interval [a, b] into n equal sub-intervals (where n must be even) of width h = (bโa)/n. Over each pair of sub-intervals (three points), a second-degree polynomial (parabola) is fitted and integrated exactly.
๐ Definition โ Simpsonโs 1/3 Rule: A numerical integration method that uses parabolas to approximate the area under a curve, requiring an even number of sub-intervals.
๐ Formula: [ I = \frac{h}{3} \left[ f_0 + 4f_1 + f_2 \right] \quad \text{(for one pair of sub-intervals)} ] Extended formula for n sub-intervals: [ I = \frac{h}{3} \left[ f(a) + f(b) + 4 \sum_{\text{odd indices}} f(x_k) + 2 \sum_{\text{even indices}} f(x_k) \right] ] Where:
- ( h ) = step size = (bโa)/n
- ( f(a) ) = function value at lower limit
- ( f(b) ) = function value at upper limit
- Odd indices (k=1,3,5,...) are multiplied by 4
- Even indices (k=2,4,6,...) are multiplied by 2
๐ก Why this matters: The 4:2:1 weighting pattern is the signature of Simpsonโs rule โ getting this pattern correct is the most common source of programming error.
๐ Example: For the function f(x) = xยณ with a=0, b=3, and n=16:
- h = (3โ0)/16 = 0.1875
- f(a) = f(0) = 0
- f(b) = f(3) = 27
- Odd terms (k=1,3,5,...,15): f(0.1875), f(0.5625), f(0.9375), ... โ multiplied by 4
- Even terms (k=2,4,6,...,14): f(0.375), f(0.75), f(1.125), ... โ multiplied by 2
- Answer = (h/3) ร [f(0) + f(3) + 4ร(sum of odd terms) + 2ร(sum of even terms)]
MATLAB Implementation
The MATLAB code implements Simpsonโs 1/3 Rule with the following structure:
- Function definition:
f=@(x)x^3;โ user changes this for different functions - Input collection: Prompts user for a, b, and n
- Validation check:
if rem(n,2)==1โ checks if n is odd; if so, prompts user to re-enter n as an even number - Odd and even term separation: Uses
rem(k,2)==1to identify odd-indexed terms (added toso) and even-indexed terms (added tose) - Final computation:
answer = h/3 * (f(a) + f(b) + 4*so + 2*se)
๐ Definition โ rem(n,2): The MATLAB function that returns the remainder when n is divided by 2; if remainder is 1, n is odd; if 0, n is even.
๐ก Why this matters: The if rem(n,2)==1 check ensures the fundamental requirement of Simpsonโs rule is satisfied โ an odd n would make the method invalid, as the 1/3 rule requires pairing sub-intervals.
๐ Example of validation: For input n=17 (odd):
rem(17,2)returns 1- Program prints:
Enter valid n!!! - Prompts:
Enter n as even number - User must re-enter, e.g., n=16
โญ Key Takeaways
Simpsonโs 1/3 Rule provides more accurate numerical integration than the trapezoidal rule because it uses parabolic interpolation instead of linear interpolation. The critical requirement is that n must be even โ this is non-negotiable for the method to work. The MATLAB implementation correctly separates odd-indexed terms (multiplied by 4) from even-indexed terms (multiplied by 2), with the endpoints f(a) and f(b) each having weight 1. The formula pattern h/3 ร [first + last + 4(odds) + 2(evens)] must be memorized exactly for exams.
๐ง Quick Revision Questions
- What is the requirement for the number of sub-intervals n when using Simpsonโs 1/3 Rule, and why is this requirement necessary?
- Write the complete formula for Simpsonโs 1/3 Rule for n sub-intervals, clearly showing the coefficients for odd and even terms.
- In the MATLAB code, how does the program check if n is odd, and what does it do if it finds an odd value?
- For the function f(x)=xยณ with a=0, b=3, and n=4, what are the x-values at odd indices and even indices?
- Why are odd-indexed terms multiplied by 4 while even-indexed terms are multiplied by 2 in Simpsonโs rule?