π Lecture 10 β Matrices in MATLAB
π Overview: This lecture introduces matrices in MATLAB, covering how to create vector and matrix variables, perform basic operations like summing rows and columns, and execute matrix algebra tasks such as multiplication, determinant calculation, and inversion. Understanding these fundamentals is essential for numerical computing and solving linear algebra problems in engineering and science.
ποΈ Topics Covered
This lecture covers creating row and column vectors using explicit lists and the colon operator with step values, creating matrices with square brackets and semicolons, performing sums on columns and rows using the sum command and transpose, extracting diagonal elements with diag, and executing matrix multiplication using both for loops and the asterisk operator, along with computing determinants and inverses using det and inv.
π Lecture Summary
Matrices in MATLAB β Creating Vector and Matrix Variables
Matrices can be entered by an explicit list of elements, generated by built-in functions, loaded from external data, or created by M-files. The basic conventions for entering matrices are: elements of a row are separated by commas or spaces, a semicolon indicates the end of each row, and the entire list is surrounded by square brackets [ ].
Row vectors are created by putting values in square brackets, separated by spaces or commas. For example:
rowvec = [2,4,5,6]
Output: rowvec = 2 4 5 6
Row vectors can also be generated using the colon operator :, which iterates from a starting value to an ending value with a default step of one. Square brackets are not necessary. For example:
colvec = 2:6
Output: colvec = 2 3 4 5 6
A step value can be specified in the colon operator: start:step:end. For example:
stepvec = 2:2:10
Output: stepvec = 2 4 6 8 10
Column vectors can be created in two ways: by putting values in square brackets separated by semicolons, or by creating a row vector and then transposing it using the apostrophe ' (the transpose operator). For example:
colvec = [2;5;10]
Output:
colvec =
2
5
10
Alternatively:
Rowvec = [2,5,10]
colvec = Rowvec'
Produces the same column vector.
π Definition β Colon Operator: start:step:end generates a sequence of numbers from start to end with increments of step. If step is omitted, it defaults to 1.
π Formula: vector = start:step:end β creates a row vector with values start, start+step, start+2*step, ... up to the largest value not exceeding end.
π Example: v = 1:2:7 produces v = [1, 3, 5, 7].
Matrices β Some useful operations on matrices
Matrix variables are created with values in square brackets, rows separated by semicolons, and elements within rows separated by spaces or commas. Every row must have the same number of values. For example, matrix
A = [5/6, 1/6, 0; 5/6, 0, 1/6; 0, 5/6, 1/6]
can be entered numerically or symbolically using sym().
The sum command computes a row vector containing the sum of the columns of a matrix. MATLAB prefers to work with columns. For matrix A, B = sum(A) gives sums of each column. For example:
A = sym([5/6,1/6,0;5/6,0,1/6;0,5/6,1/6])
B = sum(A)
Output: B = [5/3, 1, 1/3]
To compute the sum of the row vectors of a matrix, take the transpose, compute the sum, and transpose the result. For example:
B = sum(A')
B = [1, 1, 1]
B'
Output: column vector [1; 1; 1]
The diag command produces a column vector containing the elements of the main diagonal of a matrix. For example:
B = diag(A)
Output:
B =
5/6
0
1/6
The colon operator : combined with sum can compute the sum of an individual column or row. The key word end refers to the last column or row. For example, the sum of the last column of matrix A:
B = sum(A(:,end))
Output: B = 1/3
To sum the second column: C = sum(A(:,2)).
π Definition β sum command: sum(M) returns a row vector containing the sum of each column of matrix M. sum(M') sums the rows, but must be transposed for a column result.
π Formula: sum(A(:,end)) β sums all rows of the last column of A. sum(A(1,:)) β sums all columns of the first row of A.
π Example: For A = [1 2 3; 4 5 6], sum(A) gives [5 7 9], sum(A')' gives [6; 15].
π‘ Why this matters: These basic operations allow you to quickly compute totals across data sets, extract subsets, and prepare data for more advanced linear algebra, which is fundamental in data science, engineering simulations, and statistics.
Matrix Algebra β Matrices Multiplication
Matrix multiplication can be performed using a for loop with MATLAB's colon notation and vector scalar product. For matrices A (2Γ3) and B (3Γ2):
A = [1,2,3; 4,5,6];
B = [1,4; 6,7; 0,1];
for i = 1:2
for j = 1:2
C(i,j) = A(i,:) * B(:,j);
end
end
C
Output:
C =
13 21
34 57
Alternatively, the single asterisk operator * performs matrix multiplication directly:
C = A * B
Output: C = [13 21; 34 57]
Matrix Algebra β Determinant of a matrix
The determinant of a square matrix is computed using the det command. For example:
A = sym([5/6,1/6,0; 1/6,0,5/6; 0,5/6,1])
det(A)
Output: ans = -131/216
Matrix Algebra β Inverse of a matrix
The inverse of a square matrix is computed using the inv command. For the same matrix A:
inv(A)
Output:
ans =
[ 150/131, 36/131, -30/131]
[ 36/131, -180/131, 150/131]
[ -30/131, 150/131, 6/131]
π Definition β det and inv: det(A) computes the determinant of square matrix A. inv(A) computes the inverse Aβ»ΒΉ such that A * Aβ»ΒΉ = I (identity matrix). A matrix must be square and non-singular (det β 0) for inverse to exist.
π Formula: Determinant of a 3Γ3 matrix: det(A) = aββ(aββaββ β aββaββ) β aββ(aββaββ β aββaββ) + aββ(aββaββ β aββaββ).
π Example: For A above, det = -131/216 β -0.606. Its inverse is shown above.
Exercise
Compute:
- AB using a
forloop in MATLAB, where:A = [5/6, 1/6, 0; 1/6, 0, 5/6; 0, 5/6, 1] B = [5/2, 1/2, 0; 1/3, 0, 5/3; 0, 5/6, 1] - The sum of the second column of matrix C using the
sumcommand:C = [1, 1/2, 0; 1/3, 1/6, 2; 0, 0, 1] - The sum of the second row of matrix C using the
sumcommand.
π‘ Why this matters: These exercise problems test your ability to apply the concepts of matrix creation, sum operations, and multiplication in practical MATLAB programming, reinforcing skills for handling real datasets and solving systems of equations.
β Key Takeaways
This lecture introduces MATLAB as a powerful tool for matrix computations. The key takeaways are: understanding how to create row and column vectors using both explicit lists and the colon operator with step values; mastering matrix creation with square brackets and semicolons; learning to compute sums of columns (with sum) and rows (with sum and transpose); extracting diagonal elements with diag; and performing matrix algebra including multiplication (via for loops or the * operator), determinants (det), and inverses (inv). These operations form the backbone of numerical linear algebra and are essential for solving engineering and scientific problems.
π§ Quick Revision Questions
- How do you create a row vector with elements 1, 3, 5, 7, 9 using the colon operator in MATLAB?
- What is the difference between creating a column vector with semicolons versus using the transpose of a row vector?
- How does the
sumcommand behave on a matrix, and how do you compute the sum of each row instead of each column? - What does the command
sum(A(:,end))compute, and what does the keywordendrepresent? - Given matrices A (2Γ3) and B (3Γ2), write the MATLAB code to multiply them using a
forloop and using the asterisk operator.
π Lecture 11 β Eigen Values and Eigen Vectors
π Overview: This lecture provides a comprehensive introduction to computing eigenvalues and eigenvectors using MATLAB, along with methods for solving systems of linear equations. It covers reduced row echelon form, elementary row operations, and spanning sets, demonstrating how MATLAB's built-in functions can efficiently perform these linear algebra operations.
ποΈ Topics Covered
The lecture covers computing eigenvalues and eigenvectors using the eig command in MATLAB, finding reduced row echelon form using rref, solving systems of linear equations when the coefficient matrix has an inverse, performing elementary row operations manually, and using rref to determine if a vector is in the span of a set. It also includes for loops, nested loops, derivatives, integration, and differential equation solving in MATLAB.
π Lecture Summary
Eigen Values and Eigen Vectors
The eig command is used to determine the eigenvalues of a square matrix in MATLAB. With slight modification, it also determines the associated eigenvectors. The columns of matrix P denote the eigenvectors, and matrix D denotes the diagonal matrix having eigenvalues on the main diagonal.
π Definition β Eigenvalues and Eigenvectors: For a square matrix B, eigenvalues Ξ» satisfy Bv = Ξ»v where v is the corresponding eigenvector. The eig(B) command returns eigenvalues, while [P,D] = eig(B) returns both eigenvectors (as columns of P) and eigenvalues (on diagonal of D).
π Formula: [P,D] = eig(B) β P contains eigenvectors as columns, D is diagonal matrix with eigenvalues
π Example: For matrix B =
0 1 3
2 4 1
6 1 8
The MATLAB code is:
B=[0,1,3;2,4,1;6,1,8];
eig(B)
[P,D]=eig(B)
Results: Eigenvalues are -1.9716, 10.1881, and 3.7835. The eigenvector matrix P has corresponding eigenvectors as columns.
π‘ Why this matters: Eigenvalues and eigenvectors are fundamental to understanding linear transformations, stability of systems, and have applications in engineering, physics, and data science.
Reduced row echelon form
MATLAB gives the reduced echelon form of a matrix using the rref command. This command transforms any matrix into its unique reduced row echelon form through elementary row operations.
π Definition β Reduced Row Echelon Form: A matrix in reduced row echelon form has leading 1s (pivots) in each row with zeros above and below each pivot, and rows of zeros at the bottom.
π Example: For matrix B =
0 1 3
2 4 1
6 1 8
Using rref(B) produces:
1 0 0
0 1 0
0 0 1
This is the 3Γ3 identity matrix.
Solution of system of linear equations
Two situations occur when solving systems: whether the coefficient matrix has an inverse or not. The lecture first discusses the case when the coefficient matrix has an inverse.
π Definition β Inverse Method: For a system AX = B where A has an inverse, the solution is X = Aβ»ΒΉB.
π Formula: X = inv(A)*B β Solution vector X equals inverse of coefficient matrix times constant vector
π Example: Solve the system:
xβ + 3xβ = -2
2xβ + 4xβ = 1
Coefficient matrix A = [1,3;2,4], B = [-2;1] MATLAB code:
A=sym([1,3;2,4]);
B=sym([-2;1]);
C=inv(A);
X=C*B
Solution: X = [11/2, -5/2]α΅
π Example: Solve system using solve command:
3x + 2y + z = 1
y = 2
x + 2y = 3
MATLAB code:
eqn1='3*x+2*y+z=1';
eqn2='y=2';
eqn3='x+2*y=3';
sol=solve(eqn1,eqn2,eqn3);
X=double([sol.x,sol.y,sol.z])'
Solution: X = [-1; 2; 0]
Elementary row operations
The matrix can be converted into reduced echelon form manually using row operations. Elementary row operations include: multiplying a row by a constant, swapping rows, and adding a multiple of one row to another.
π Definition β Elementary Row Operations: Operations performed on augmented matrices to reduce them to row echelon form: (1) Multiply a row by a nonzero scalar, (2) Add a multiple of one row to another, (3) Swap two rows.
π Example: For the system:
3x + 2y + z = 1
y = 2
x + 2y = 3
Enter as augmented matrix Ab. MATLAB code for manual reduction:
A=[3,2,1;0,1,0;1,2,0];
b=[1,2,3]';
Ab=[A b];
Ab(1,:)=1/3*Ab(1,:);
Ab(3,:)=Ab(3,:)-Ab(1,:);
Ab(1,:)=Ab(1,:)-0.6667*Ab(2,:);
Ab(3,:)=Ab(3,:)-1.3333*Ab(2,:);
Ab(3,:)=1/-0.3333*Ab(3,:);
Ab(1,:)=Ab(1,:)-0.3333*Ab(3,:)
Resulting reduced echelon form gives solution: x=-1, y=2, z=0.
Spanning set
The rref command is used to check whether a vector can be written as a linear combination of elements of a set. If the system is consistent (no contradictory rows), the vector is in the span.
π Definition β Span: A vector v is in the span of a set of vectors {vβ, vβ, ..., vβ} if v can be expressed as a linear combination of those vectors: v = wβvβ + wβvβ + ... + wβvβ.
π Example: Show that [a; b] is in the span of [β2,1; 1,6] for any a and b. MATLAB code:
syms a b
A=[-2,1;1,6];
b=[a;b];
Ab=[A b];
rref(Ab)
The weights are:
wβ = b/13 - 6a/13
wβ = a/13 + 2b/13
The system is consistent for any a and b, so [a; b] is always in the span.
For Loops
For loops are counter-based loops in MATLAB. The syntax is for k=start:step:end followed by statements and end.
π Definition β For Loop: A control structure that repeats a block of code a specified number of times using a counter variable.
π Example: Add elements of vector v = 1:10
v = 1:10;
sum = 0;
for i = 1:length(v)
sum = sum + v(i);
end
disp(sum)
Output: 55
π Example: Add only odd numbers from 1:10
sum = 0;
for i = 1:2:10
sum = sum + i;
end
disp(sum)
Output: 25
π Example: Compute factorial of a non-negative number
numb=input('Enter a number: ');
fact=1;
if numb<0
fprintf('the number you have entered is negative');
else
for i=1:numb
fact=fact*i;
end
fact
end
Nested Loops
Nested loops are loops within loops, useful for creating patterns or processing multi-dimensional data.
π Example: Print a pattern of stars with user-specified rows
rows=input('How many rows do you want: ');
for R=1:rows
for s=1:R
fprintf('*');
end
fprintf('\n');
end
Derivatives in MATLAB
The diff command computes derivatives of symbolic expressions.
π Example: First derivative
syms x
f = sin(5*x);
diff(f) % Results: 5*cos(5*x)
π Example: Second derivative
syms x
g = exp(x)*cos(x);
diff(g,2)
π Example: Partial derivative
syms s t
f = sin(s*t);
diff(f,t) % Partial derivative βf/βt
Integration in MATLAB
The int command computes integrals of symbolic expressions.
π Example: Indefinite integral
syms x
int(x^n) % or int(x^n,x)
π Example: Definite integral
syms x
int(sin(2*x), 0, pi/2) % or int(sin(2*x), x, 0, pi/2)
Differential Equations with dsolve
The dsolve command solves ordinary differential equations symbolically.
π Definition β dsolve: Solves differential equations using symbolic computation. Syntax: S = dsolve(eqn) or S = dsolve(eqn, cond) for initial conditions.
π Example: First-order ODE dy/dt = ty, y(0) = 2
syms y(t)
ode = diff(y,t) == t*y;
cond = y(0) == 2;
ySol(t) = dsolve(ode,cond)
π Example: dy/dt + 4y = eβ»α΅, y(0) = 1
syms y(t)
ode = diff(y)+4*y == exp(-t);
cond = y(0) == 1;
ySol(t) = dsolve(ode,cond)
π Example: System of differential equations
syms u(t) v(t)
ode1 = diff(u) == 3*u + 4*v;
ode2 = diff(v) == -4*u + 3*v;
odes = [ode1; ode2];
[uSol(t), vSol(t)] = dsolve(odes)
With initial conditions u(0)=0, v(0)=0:
cond1 = u(0) == 0;
cond2 = v(0) == 0;
conds = [cond1; cond2];
[uSol(t), vSol(t)] = dsolve(odes,conds)
π Example: Second-order ODE dΒ²y/dxΒ² = cos(2x)-y, y(0)=1, y'(0)=0
syms y(x)
Dy = diff(y);
ode = diff(y,x,2) == cos(2*x)-y;
cond1 = y(0) == 1;
cond2 = Dy(0) == 0;
conds = [cond1 cond2];
ySol(x) = dsolve(ode,conds);
ySol = simplify(ySol)
π Example: Third-order ODE dΒ³u/dxΒ³ = u, u(0)=1, u'(0)=-1, u''(0)=Ο
syms u(x)
Du = diff(u,x);
D2u = diff(u,x,2);
ode = diff(u,x,3) == u;
cond1 = u(0) == 1;
cond2 = Du(0) == -1;
cond3 = D2u(0) == pi;
conds = [cond1 cond2 cond3];
uSol(x) = dsolve(ode,conds)
β Key Takeaways
The lecture demonstrates MATLAB's powerful symbolic and numerical capabilities for linear algebra and differential equations. Key commands include eig for eigenvalue/eigenvector computation, rref for reduced row echelon form and spanning set verification, inv for solving systems with invertible coefficient matrices, and dsolve for solving ordinary differential equations with initial conditions. Understanding when to use symbolic (sym, syms) versus numerical computation is crucial. The solve command provides an alternative for systems of equations, while elementary row operations can be performed manually for educational purposes. For spanning sets, the consistency of the rref output determines whether a vector is in the span.
π§ Quick Revision Questions
- What MATLAB command computes both eigenvalues and eigenvectors of a matrix, and how do you extract each separately?
- How does the
rrefcommand help determine if a vector is in the span of a set of vectors? - When solving a system of linear equations AX = B, what condition must the coefficient matrix A satisfy for X = inv(A)*B to work?
- What is the difference between using
solveand using the inverse method for solving systems of equations in MATLAB? - How do you specify initial conditions when using
dsolveto solve a second-order ordinary differential equation?
π Lecture 12 β Numerical Solutions of ODEs in MATLAB Using ODE45
π Overview: This lecture introduces the numerical solution of ordinary differential equations (ODEs) when exact solutions are not available. It focuses on using MATLABβs
ode45command to solve first-order ODEs and initial value problems (IVPs), including how to specify the ODE, time interval, and initial conditions, as well as how to plot families of solutions.
ποΈ Topics Covered
The lecture covers the motivation for numerical ODE solutions, the syntax and usage of the ode45 command, specifying anonymous functions for single-component ODEs, solving a simple ODE with given initial conditions and time interval, plotting the numerical solution, and plotting a family of approximate solutions for an IVP with multiple initial conditions.
π Lecture Summary
Numerical Solutions of ODEs in MATLAB Using ODE45
Sometimes it is not possible to find the exact solution of certain differential equations. In such cases, we are forced to compute their numerical solutions. To find the numerical solutions of first-order ordinary differential equations, we use the ode45 command.
π Definition β ode45: [t,y] = ode45(odefun, tspan, y0) where tspan = [t0 tf] integrates the system of differential equations y' = f(t,y) from t0 to tf with initial conditions y0. Each row in the solution array y corresponds to a value returned in column vector t.
Example β Simple ODE with Anonymous Function
Simple ODEs that have a single solution component can be specified as an anonymous function in the call to the solver. The anonymous function must accept two inputs (t,y) even if one of the inputs is not used.
π Define anonymous function: @(t,y) 2*t β this creates a function of t and y that returns 2*t, even though y is not used in this specific ODE.
Solve the ODE: y' = 2t. Use a time interval of [0,5] and the initial condition y0 = 0.
tspan = [0 5];
y0 = 0;
[t,y] = ode45(@(t,y) 2*t, tspan, y0);
π Example: After running the code, t will contain time points from 0 to 5 (e.g., 0, 0.125, 0.25, ...) and y will contain the corresponding numerical solution values. This can be plotted using plot(t,y) to visualize the solution curve.
Example β Family of Approximate Solutions
Plot the family of approximate solutions of the following IVP:
y'(x) = y - xΒ² + 1, y(0) = 0.5 : 0.2 : 3
This means we have multiple initial conditions starting at y=0.5 and increasing by steps of 0.2 up to y=3. The values are: 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2.1, 2.3, 2.5, 2.7, 2.9, 3.0.
f = @(x,y) y - x^2 + 1;
ode45(f, [0,2], 0.5:0.2:3)
π Definition β Family of solutions: When multiple initial conditions are provided as a vector (e.g., 0.5:0.2:3), ode45 solves the ODE for each initial condition separately, producing a family of solution curves on the same plot.
π Example: The ODE y' = y - xΒ² + 1 is solved from x=0 to x=2 for each initial value in the range [0.5, 3.0] in steps of 0.2. The ode45 command automatically plots all resulting solution curves, showing how different starting points affect the trajectory.
π‘ Why this matters: Plotting families of solutions helps visualize how the system behaves for different initial conditions, revealing patterns such as convergence, divergence, or equilibrium behavior.
β Key Takeaways
Students must remember that ode45 is MATLABβs primary tool for numerically solving first-order ODEs when exact solutions are unavailable. The syntax [t,y] = ode45(odefun, tspan, y0) requires three inputs: the ODE function (often an anonymous function), the time span vector [t0 tf], and the initial condition(s). Anonymous functions for single-component ODEs must accept two inputs (t,y) even if one is unused, as in @(t,y) 2*t. The solver automatically handles numerical integration and returns arrays of time points and corresponding solution values. For multiple initial conditions, providing a vector of initial values generates a family of solution curves, which is useful for exploring system behavior under different starting conditions.
π§ Quick Revision Questions
- What is the syntax for the
ode45command in MATLAB, and what do the three main inputs represent? - Why must an anonymous function passed to
ode45always accept two inputs(t,y), even if one is not used in the equation? - How would you use
ode45to solve the ODEy' = t^2 + 1from t=0 to t=3 with initial condition y(0)=4? - If you provide a vector of initial conditions (e.g.,
y0 = 0:0.5:3), what doesode45do differently compared to a single initial condition? - In the example
y'(x) = y - x^2 + 1, what is the time interval and what are the initial conditions being solved?
π Lecture 13 β Solve ODE with Multiple Initial Conditions
π Overview: This lecture demonstrates how to solve a single ordinary differential equation (ODE) for multiple different initial conditions simultaneously using MATLAB's
ode45solver. It shows how to vectorize the initial condition input and plot all solution curves together, which is essential for understanding how a system behaves from different starting points.
ποΈ Topics Covered
The lecture covers defining an ODE as an anonymous function, creating a vector of initial conditions, solving the ODE for all initial conditions at once using ode45, and plotting the family of solution curves on the same graph.
π Lecture Summary
Solving an ODE with Multiple Initial Conditions
The problem is to solve the first-order ordinary differential equation (ODE): y'(x) = β2y + 2 cos(t) sin(2t)
A vector of different initial conditions is created in the range [β5, 5]. The equation is solved for each initial condition over the time interval [0, 3] using the MATLAB solver ode45.
First, the ODE is defined as an anonymous function (also called a function handle):
yprime = @(t,y) -2*y + 2*cos(t).*sin(2*t);
- The
@(t,y)creates a function handle that accepts timetand statey - Note the use of element-wise multiplication
.*inside the function
Next, the time span and initial conditions are defined:
tspan = [0 3];
y0 = -5:5;
tspandefines the time interval from 0 to 3y0 = -5:5creates a vector of initial conditions:[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]β a total of 11 different initial values
Then, ode45 is called with these inputs:
[t,y] = ode45(yprime,tspan,y0);
- π‘ Why this matters: MATLAB's
ode45automatically handles the vector of initial conditions. Wheny0is a vector of length 11, the outputybecomes an NΓ11 matrix, where each column corresponds to the solution for one initial condition. The time vectortremains a single column vector of length N.
Finally, the results are plotted:
plot(t,y)
- This single command plots all 11 solution curves on the same figure
- Each curve represents the solution starting from a different initial condition
- The plot shows how solutions with different starting values evolve over time
π Definition β ode45: MATLAB's numerical ODE solver based on the Dormand-Prince method (an explicit Runge-Kutta formula of order 4/5). It automatically selects step size to maintain accuracy.
π Key concept: When y0 is a vector (multiple initial conditions), ode45 solves the ODE for each initial condition in a single call, returning y as a matrix where each column is one solution trajectory.
π Example: For initial conditions y0 = -5:5 (values -5 through 5), ode45(yprime, tspan, y0) returns t as an NΓ1 vector and y as an NΓ11 matrix. The first column of y is the solution starting at y=-5, the second column is the solution starting at y=-4, and so on.
β Key Takeaways
The most critical thing to remember is that ode45 can accept a vector of initial conditions and will solve the ODE for all of them simultaneously, returning the outputs as a matrix where each column corresponds to one initial condition. This vectorized approach is far more efficient than looping over each initial condition individually. The time vector t remains a single column shared by all solutions. A single plot(t,y) command plots all solution curves together, allowing easy visualization of how the system behaves from different starting points.
π§ Quick Revision Questions
- What does the anonymous function
@(t,y)indicate in MATLAB? - What type of data structure does
ybecome when solving an ODE with 11 initial conditions usingode45? - Why is element-wise multiplication (
.*) used inside the ODE function? - What does
y0 = -5:5create as a vector of initial conditions? - How can you plot all solution curves from multiple initial conditions with a single command?
π Lecture 14 β Third-Order ODE with Initial Conditions
π Overview: This lecture demonstrates how to solve a third-order ordinary differential equation with three initial conditions using MATLAB's Symbolic Math Toolbox. It shows the complete workflow from defining symbolic variables and derivatives to applying boundary conditions and obtaining the analytical solution.
ποΈ Topics Covered
This lecture covers the step-by-step solution of a third-order ODE (dΒ³u/dxΒ³ = u) with three initial conditions (u(0)=1, uβ²(0)=β1, uβ³(0)=Ο) using syms, diff, and dsolve functions in MATLAB, including the definition of the ODE, its first and second derivatives, and the combined application of all initial conditions.
π Lecture Summary
Third-Order ODE with Initial Conditions
The symbolic variable u(x) is first declared using symsu(x). The first derivative Du is defined as diff(u,x) and the second derivative D2u as diff(u,x,2). The third-order ODE is written as diff(u,x,3) == u, meaning the third derivative of u with respect to x equals u itself. Three initial conditions are then specified: u(0) = 1, Du(0) = -1, and D2u(0) = pi. These conditions are stored in a vector conds = [cond1 cond2 cond3]. Finally, dsolve(ode, conds) computes the analytical solution uSol(x) that satisfies both the differential equation and all three initial conditions.
π Definition β Symbolic variable: A MATLAB variable declared with syms that allows exact symbolic computation rather than numerical approximation.
π Formula: dsolve(ode, conds) β Returns the analytical solution of the ODE that satisfies all specified initial conditions.
π Example: Solve dΒ³u/dxΒ³ = u with u(0)=1, uβ²(0)=-1, uβ³(0)=Ο.
Steps:
- Declare
syms u(x)to define symbolic variable - Define
Du = diff(u,x),D2u = diff(u,x,2)for derivatives - Set ODE:
ode = diff(u,x,3) == u - Set conditions:
cond1 = u(0)==1,cond2 = Du(0)==-1,cond3 = D2u(0)==pi - Combine conditions:
conds = [cond1 cond2 cond3] - Solve:
uSol(x) = dsolve(ode, conds)β outputs the exact analytical solution
π‘ Why this matters: Solving higher-order ODEs with multiple initial conditions is essential in physics and engineering for modeling systems like beam deflection, circuit dynamics, and fluid flow where position, velocity, and acceleration are all specified at a starting point.
β Key Takeaways
The critical requirement for solving any nth-order ODE is providing exactly n initial conditions β here three conditions for a third-order equation. The key workflow involves first defining the symbolic variable and its derivatives, then writing the ODE using the diff command, specifying each initial condition separately, combining them in an array, and finally calling dsolve with both the equation and conditions. The solution uSol(x) represents the unique function that simultaneously satisfies the differential equation and all boundary conditions. This method works for linear and many nonlinear ODEs, providing exact symbolic solutions rather than numerical approximations.
π§ Quick Revision Questions
- How many initial conditions are needed for a third-order ODE, and why?
- What MATLAB function is used to declare a symbolic variable for differentiation?
- What is the correct syntax to define the third derivative of
uwith respect toxin MATLAB? - How are multiple initial conditions combined before passing to
dsolve? - What would happen if you provided only two initial conditions instead of three to
dsolve?
π Lecture 15 β Solve a System of Differential Equations
π Overview: This lecture demonstrates how to solve systems of linear first-order differential equations using MATLAB's symbolic toolbox. It covers the complete workflow from defining equations with symbolic functions, applying initial conditions, and visualizing solutions, while also distinguishing between explicit and implicit solution forms.
ποΈ Topics Covered
The lecture covers solving coupled first-order differential equations using dsolve, defining symbolic functions and equations, applying initial conditions to determine constants, visualizing solutions with fplot, and understanding the difference between explicit and implicit solution forms.
π Lecture Summary
Solve a System of Differential Equations
The lecture begins with an example system of two linear first-order differential equations:
- du/dt = 3u + 4v
- dv/dt = β4u + 3v
First, represent u and v using symsu(t) v(t) to create symbolic functions u(t) and v(t). Define the equations using == and represent differentiation using the diff function.
ode1 = diff(u) == 3*u + 4*v;
ode2 = diff(v) == -4*u + 3*v;
odes = [ode1; ode2]
S = dsolve(odes)
To access u(t) and v(t), index into the structure S:
uSol(t) = S.u
vSol(t) = S.v
Alternatively, store u(t) and v(t) directly by providing multiple output arguments:
[uSol(t), vSol(t)] = dsolve(odes)
The constants C1 and C2 appear because no conditions are specified. Solve the system with the initial conditions u(0) == 0 and v(0) == 1. The dsolve function finds values for the constants that satisfy these conditions.
cond1 = u(0) == 0;
cond2 = v(0) == 1;
conds = [cond1; cond2];
[uSol(t), vSol(t)] = dsolve(odes, conds)
π‘ Why this matters: Without initial conditions, the solution contains arbitrary constants; initial conditions uniquely determine the specific solution for a given physical scenario.
Visualize the solution using fplot:
fplot(uSol)
hold on
fplot(vSol)
grid on
legend('uSol','vSol','Location','best')
Explicit and Implicit Solutions
π Definition β Explicit solution: Any solution given in the form y = y(t). In other words, the only place that y actually shows up is once on the left side and only raised to the first power.
π Definition β Implicit solution: Any solution that isn't in explicit form.
An explicit solution directly expresses the dependent variable in terms of the independent variable, making evaluation straightforward. An implicit solution may involve the dependent variable in a more complex relationship (e.g., F(t, y) = 0) that requires additional manipulation to solve for y explicitly.
β Key Takeaways
When solving systems of differential equations in MATLAB, always begin by defining symbolic functions with symsu(t) v(t) and representing derivatives using diff. Use dsolve to obtain symbolic solutions, which will include arbitrary constants if no initial conditions are provided. Apply initial conditions as separate equations using == (e.g., u(0) == 0) and pass them to dsolve to determine unique constants. Visualize solutions with fplot and remember the critical distinction: an explicit solution gives y directly as a function of t, while an implicit solution does not β this distinction affects how you interpret and use the solution.
π§ Quick Revision Questions
- What MATLAB function is used to solve a system of differential equations symbolically?
- How do you define symbolic functions u(t) and v(t) before setting up the differential equations?
- What happens to the general solution if no initial conditions are provided to
dsolve? - How do you apply initial conditions u(0) = 0 and v(0) = 1 to the system?
- What is the difference between an explicit solution and an implicit solution?
π Lecture 16 β Find Explicit and Implicit Solutions of Differential Equation
π Overview: This lecture covers methods for finding both explicit and implicit solutions of differential equations, including when explicit solutions are not analytically obtainable. It introduces the Lambert W function for explicit solutions and demonstrates when to use MATLAB's
dsolvefunction with the 'Implicit' option, as well as numerical solvers likeode45for cases where symbolic solutions fail.
ποΈ Topics Covered
The lecture explores finding explicit and implicit solutions of differential equations using MATLAB's dsolve function, including cases where explicit solutions involve the Lambert W function. It covers solving differential equations when no explicit analytical solution exists by using the 'Implicit' option or numerical solvers. Finally, it introduces the ode45 command for numerical solutions of first-order ordinary differential equations.
π Lecture Summary
Example β Find Explicit and Implicit Solutions of Differential Equation
The lecture begins with an example initial-value problem: $yy' = -x$, $y(0) = r$, where $r$ is constant. The implicit solution is $x^2 + y^2 = r^2$, which defines $y(x)$ implicitly through an equation involving $y(x)$. The explicit solution is $y(x) = \pm \sqrt{r^2 - x^2}$, which directly expresses $y$ as a function of $x$.
Solve the Differential Equation Using dsolve
When solving $\frac{\partial}{\partial t} y(t) = e^{-y(t)} + y(t)$, dsolve returns an explicit solution in terms of a Lambert W function that has a constant value. The MATLAB code is:
syms y(t)
eqn = diff(y) == y + exp(-y)
sol = dsolve(eqn)
To return implicit solutions of the differential equation, set the 'Implicit' option to true:
sol = dsolve(eqn, 'Implicit', true)
Find Implicit Solution When No Explicit Solution Is Found
If dsolve cannot find an explicit solution of a differential equation analytically, it returns an empty symbolic array. For example:
syms y(x)
eqn = diff(y) == (x - exp(-x))/(y(x) + exp(y(x)));
S = dsolve(eqn)
This returns: Warning: Unable to find symbolic solution. S = [ empty sym]
In such cases, you can solve the differential equation by using a MATLAB numerical solver such as ode45. Alternatively, you can try finding an implicit solution by specifying the 'Implicit' option to true:
S = dsolve(eqn, 'Implicit', true)
Numerical Solutions of ODEs in MATLAB Using ODE45
Sometimes it is not possible to find the exact solution of certain differential equations. In this case, we are forced to compute their numerical solutions. To find the numerical solutions of first-order ordinary differential equations, we use the ode45 command:
[t, y] = ode45(odefun, tspan, y0)
where tspan = [t0 tf] integrates the system of differential equations $y' = f(t, y)$ from $t_0$ to $t_f$ with initial conditions $y_0$. Each row in the solution array $y$ corresponds to a value returned in column vector $t$.
π Definition β Lambert W function: A special function defined as the inverse of $f(w) = we^w$, used to express explicit solutions of certain differential equations.
π Formula: $[t, y] = ode45(odefun, tspan, y0)$ β This command numerically integrates the ODE system from initial time $t_0$ to final time $t_f$ using initial conditions $y_0$.
π Example: For the ODE $y' = \frac{x - e^{-x}}{y + e^y}$ with no explicit symbolic solution, use ode45 with appropriate odefun, tspan, and y0 to obtain numerical approximations of $y$ at discrete time points stored in the column vectors $t$ and $y$.
π‘ Why this matters: Many real-world differential equations cannot be solved analytically, so knowing when to use implicit solutions or numerical methods like ode45 is essential for practical engineering and scientific computation.
β Key Takeaways
The most critical concepts from this lecture are: (1) Differential equations may have both implicit and explicit solutions, with implicit solutions defining $y$ through an equation rather than a direct formula. (2) MATLAB's dsolve can return explicit solutions using special functions like the Lambert W function, or implicit solutions using the 'Implicit' option. (3) When no symbolic solution exists, dsolve returns an empty array, requiring either implicit solution methods or numerical approaches. (4) The ode45 command provides numerical solutions for first-order ODEs using the syntax [t,y] = ode45(odefun,tspan,y0). (5) For exam purposes, you must know when to choose explicit, implicit, or numerical solution methods and how to implement them in MATLAB.
π§ Quick Revision Questions
- What is the difference between an implicit and an explicit solution of a differential equation?
- When would
dsolvereturn an empty symbolic array, and what are two alternative approaches to solve such equations? - What does the Lambert W function represent, and in what type of solution does it typically appear?
- Write the general syntax for the
ode45command and explain what each parameter represents. - How does the 'Implicit' option in
dsolvechange the output compared to the default setting?
π Lecture 17 β Solving ODEs with MATLAB
π Overview: This lecture demonstrates how to solve simple ordinary differential equations (ODEs) using MATLAB's built-in solvers. It focuses on specifying ODEs as anonymous functions and using the
ode45solver, which is essential for numerical computation in engineering and science.
ποΈ Topics Covered
The lecture covers solving simple ODEs with a single solution component using anonymous functions in MATLAB's ode45 solver, including specifying the time interval and initial condition, and plotting the resulting solution.
π Lecture Summary
Example
Simple ODEs that have a single solution component can be specified as an anonymous function in the call to the solver. The anonymous function must accept two inputs (t,y) even if one of the inputs is not used.
Solve the ODE: yβ² = 2t
Use a time interval of [0,5] and the initial condition yβ = 0.
tspan = [0 5];
y0 = 0;
[t,y] = ode45(@(t,y) 2*t, tspan, y0);
Plot the solution.
π Definition β Anonymous function: A function defined inline in MATLAB without a separate function file, using the @(arguments) expression syntax.
π Formula: ode45(@(t,y) 2*t, tspan, y0) β The solver ode45 numerically integrates the ODE yβ²=2t from t=0 to t=5, starting from y=0.
π Example: For the ODE yβ²=2t with tspan=[0,5] and yβ=0:
- The anonymous function
@(t,y) 2*tdefines the right-hand side - The analytical solution is y(t) = tΒ² (since integrating 2t gives tΒ² + C, and with y(0)=0, C=0)
- At t=5, y=25
π‘ Why this matters: Even though y is not used in this ODE, the anonymous function must still accept both (t,y) inputs because MATLAB solvers always pass both arguments to the function.
β Key Takeaways
The most critical concepts from this lecture are: MATLAB's ode45 solver requires an ODE to be defined as a function that accepts two inputs (t,y), even if one is unused; the time interval is specified as a vector [t_start t_end]; the initial condition is a scalar for single-component ODEs; anonymous functions provide a concise way to define simple ODEs directly in the solver call; and the solver returns both time points and corresponding solution values that can be plotted.
π§ Quick Revision Questions
- What two inputs must the anonymous function for
ode45accept? - How do you specify the time interval when calling
ode45? - What does the output variable
yrepresent in theode45output? - For the ODE yβ²=2t with yβ=0, what is the analytical solution?
- Why must the anonymous function accept two inputs even if one is unused?
π Lecture 18 β Example
π Overview: This lecture demonstrates how to solve initial value problems (IVPs) with multiple initial conditions simultaneously using MATLAB's
ode45solver. It shows how to efficiently compute and plot families of solutions by passing a vector of initial conditions, which is critical for parametric studies and sensitivity analysis in differential equations.
ποΈ Topics Covered
Plotting families of approximate solutions for IVPs with multiple initial conditions using ode45. Creating anonymous functions for ODEs. Defining a vector of initial conditions. Solving ODEs over a specified time interval. Visualizing multiple solution curves on the same plot.
π Lecture Summary
Example
This example demonstrates how to plot a family of approximate solutions for the IVP given by y'(x) = y - xΒ² + 1, with initial conditions y(0) ranging from 0.5 to 3 in steps of 0.2. The anonymous function f = @(x, y) y - x^2 + 1 defines the ODE, and the syntax ode45(f, [0,2], 0.5:0.2:3) tells MATLAB to solve the ODE over the interval [0,2] for each initial condition in the vector 0.5:0.2:3.
Solve ODE with Multiple Initial Conditions
This section shows how to solve the ODE y'(t) = -2y + 2cos(t)sin(2t) for multiple initial conditions. First, create an anonymous function yprime = @(t, y) -2y + 2cos(t).sin(2t). Define the time span tspan = [0 3]. Create a vector of initial conditions y0 = -5:5, which generates values from -5 to 5 in steps of 1. Then call [t, y] = ode45(yprime, tspan, y0), which solves the ODE for each initial condition and returns the solution matrix y where each column corresponds to a different initial condition. Finally, plot all solutions using plot(t, y) to visualize the entire family of solutions on one graph.
π Definition β Vector of initial conditions: A row or column vector containing multiple starting values y(0), allowing ode45 to solve the ODE for all initial conditions simultaneously.
π Formula: y'(t) = -2y + 2cos(t)sin(2t) β The ODE to be solved for each initial condition
π Example: With y0 = -5:5 and tspan = [0 3], [t,y] = ode45(yprime, tspan, y0) produces a time vector t and a matrix y where y(:,k) contains the solution for initial condition y0(k)
β Key Takeaways
Passing a vector of initial conditions to ode45 enables solving an ODE for multiple starting values in a single function call, which is efficient for generating families of solutions. The anonymous function syntax @(t,y) must use element-wise operations (like .*) when the ODE contains products of functions. The solution matrix y has dimensions (number of time steps) Γ (number of initial conditions), where each column represents a different solution trajectory. Always define time span as a two-element vector [t0 tf] and initial conditions as a vector for multiple runs. Plotting all solutions together with plot(t,y) reveals how different initial conditions affect the behavior of the same differential equation.
π§ Quick Revision Questions
- What MATLAB function is used to solve ODEs with multiple initial conditions?
- How do you create a vector of initial conditions ranging from -5 to 5?
- What does each column of the output matrix y represent when solving with multiple initial conditions?
- Why must element-wise operations (like
.*) be used in the anonymous function for this ODE? - What would happen if you passed a single initial condition instead of a vector to
ode45?
Here is the summary of the lecture based on the provided text, following the exact format requested.
π Lecture 19 β Euler's Method
π Overview: This lecture introduces Euler's Method, a fundamental numerical technique for approximating solutions to ordinary differential equations. It explains the method's derivation from a Taylor Series expansion and its practical application for finding the value of a function at a future point. This matters because many differential equations cannot be solved analytically, and Euler's Method provides a simple, first-order approach for numerical approximation.
ποΈ Topics Covered
The lecture begins by introducing Euler's Method as an approximation technique based on a truncated Taylor's Series expansion. It explains that the method takes only the first two terms of the series to predict the value of a function at the next step, simplifying the process to a straightforward iterative calculation.
π Lecture Summary
Euler's Method
Euler's Method assumes the solution is written in the form of a Taylor's Series. For a function, the Taylor's Series expansion allows us to express the value at a future point based on its value and derivatives at a current point.
For Euler's Method, we just take the first 2 terms only. This means we truncate the Taylor Series after the term involving the first derivative.
The resulting approximation is:
π Formula: y(xβ + h) β y(xβ) + h * y'(xβ)
β This formula allows us to predict the next value of y (y(xβ + h)) by adding the current value of y (y(xβ)) to the product of the step size (h) and the slope at the current point (y'(xβ)), which is the derivative.
This formula can be written more simply as:
y_{new} = y_{old} + h * (y'_{old})
where:
y_{new}is the approximated value at the next stepy_{old}is the known value at the current stephis the step sizey'_{old}is the value of the derivative at the current step, as given by the differential equation.
π‘ Why this matters: By iteratively applying this simple formula, we can "march" forward in time, approximating the solution to a differential equation at discrete points, even if no exact analytical solution exists. The accuracy of the method depends heavily on the step size h; smaller steps generally yield better approximations but require more computation.
The lecture concludes with a notation that the method will be continued in the next session, likely covering worked examples or further refinement of the technique.
β Key Takeaways
Euler's Method is a foundational numerical technique derived from truncating a Taylor Series after the first derivative term. Its core formula, y_{new} = y_{old} + h * y'_{old}, provides a simple and direct way to approximate the solution of a differential equation step-by-step. The method's accuracy is fundamentally linked to the step size h, with smaller step sizes reducing the truncation error but increasing computational cost. Understanding this method is critical as it forms the basis for more sophisticated numerical methods for ordinary differential equations.
π§ Quick Revision Questions
- How is Euler's Method derived from a Taylor Series?
- Write down the formula for Euler's Method.
- If
his the step size, what does the producth * y'_{old}represent? - What is the single most important factor affecting the accuracy of Euler's Method?
- What does the term "y_{new}" represent in the Euler's Method formula?