MTH643 — Midterm Summary (Lectures 1–22)
📘 Lecture 1 — Introduction to MATLAB
📖 Overview: This lecture introduces MATLAB as a high-performance programming and numeric computing platform used by engineers and scientists. It covers the MATLAB desktop environment, the use of toolboxes, and basic arithmetic operations, demonstrating how MATLAB can be used as a powerful calculator for technical computing.
🗂️ Topics Covered
The lecture begins with defining MATLAB and its industry applications, then explains the importance of specialized toolboxes. It details the course contents to be covered and provides a tour of the MATLAB desktop environment, including the Command Window, Workspace, Command History, and Current Folder. Finally, it covers the use of M-files and the rules for arithmetic operators and order of operations, concluding with a practical example of calculating a circle's area and circumference.
📝 Lecture Summary
What is MATLAB
MATLAB is a programming and numeric computing platform used by engineers and scientists to analyze data, develop algorithms, and create models. It is a high-performance language for technical computing that integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation.
💡 Why this matters: MATLAB is the fundamental tool you will use throughout this course for all mathematical computations and problem-solving.
Toolboxes
MATLAB features a family of application-specific solutions called toolboxes. These are comprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment to solve particular classes of problems. Areas in which toolboxes are available include signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and many others.
Course Contents
The course will cover:
- Variables and data types
- Script Files
- Conditional Statements
- Loops, Nested Loops
- Arrays
- Functions
- Plotting
- Use of MATLAB to solve Mathematical Problems
MATLAB® Desktop
The MATLAB Desktop contains several key windows:
- The Command Window is where you type MATLAB commands following the prompt:
>> - The Workspace window shows all the variables you have defined in your current session. Variables can actually be manipulated within the workspace window.
- The Command History window displays all the MATLAB commands you have used recently – even includes some past sessions.
- The Current Folder window displays all the files in whatever folder you select to be current.
You can select what is on your desktop by clicking on Layout. Go down to Command History and select docked.
M-File
An m-file, or script file, is a simple text file where you can place MATLAB commands. It allows you to save your work, is convenient for debugging, and can be run directly.
Using MATLAB® As a Calculator - Arithmetic Operators and Order of Operations
The basic arithmetic operators are: Addition (+), Subtraction (-), Multiplication (*), Division (/), and Power (^).
The Order of Operations follows the same rules from math class:
- Complete all calculations inside parenthesis or brackets using the precedent rules below
- Powers (left to right)
- Multiplication and Division (left to right)
- Addition and Subtraction (left to right)
🔑 Definition — Operator Precedence: The set of rules that determines the order in which different arithmetic operations are evaluated in a mathematical expression.
Examples:
>> 10/5*2
This is evaluated left to right: 10/5 = 2, then 2*2 = 4
>> 5*2^3+4(2)
Power first: 2^3 = 8, then 5*8 = 40, then 40+8 = 48
>> -1^4
Power before unary minus: 1^4 = 1, then -1 = -1
>> 8^1/3
Power first: 8^1 = 8, then 8/3 = 2.6667
Exercise 1
Calculate the area and circumference of a circle with a radius of 4 cm.
📐 Formula for area: πr² → Area = 50.27 cm² 📐 Formula for circumference: 2πr → Circumference = 25.13 cm
📌 Example: To calculate area: >> pi * 4^2 gives 50.2655 which rounds to 50.27. To calculate circumference: >> 2 * pi * 4 gives 25.1327 which rounds to 25.13.
⭐ Key Takeaways
MATLAB is a high-performance technical computing environment that integrates computation, visualization, and programming. The MATLAB desktop consists of the Command Window, Workspace, Command History, and Current Folder windows, each serving a specific function. Toolboxes are specialized collections of functions that extend MATLAB's capabilities for specific applications like signal processing and control systems. The order of arithmetic operations in MATLAB follows standard mathematical rules: parentheses first, then powers, then multiplication and division, and finally addition and subtraction, all evaluated left to right. M-files (script files) are simple text files that allow you to save, debug, and run MATLAB commands directly.
🧠 Quick Revision Questions
- What are the four main windows of the MATLAB Desktop and what is the function of each?
- Explain the order of operations in MATLAB. What would be the result of
2+3*4^2? - What is an m-file and why is it useful?
- What are MATLAB toolboxes and give three examples of areas they cover?
- Using the order of operations rules, calculate the result of:
>> 10 + 6 / 3 * 2^2
📘 Lecture 2 — Doing Mathematics with Matlab (I)
📖 Overview: This lecture introduces fundamental MATLAB operations for performing basic arithmetic, symbolic computation, and variable substitution. It covers how MATLAB handles calculations, the importance of the Symbolic Math Toolbox for exact arithmetic, and common input errors students may encounter, making it essential for building a strong foundation in computational mathematics.
🗂️ Topics Covered
The lecture covers four main areas: basic arithmetic operations (addition, subtraction, multiplication, division) and the ans variable; symbolic computation using the syms command and the Symbolic Math Toolbox; substitution in symbolic expressions using the subs command; and handling errors in input by recognizing correct syntax for function calls like trigonometric functions.
📝 Lecture Summary
Arithmetic
MATLAB can perform basic arithmetic operations using standard operators. The + command is used for addition, - for subtraction, / for division, and ***** for multiplication. MATLAB automatically prints the result of each calculation and assigns it to a variable called ans.
🔑 Definition — ans variable: A default variable in MATLAB that stores the result of the most recent calculation. It is automatically overwritten with each new computation.
📐 Formula: sqrt(ans) → Takes the square root of the previous answer
📌 Example: After computing 5^3 + (5-4)/10 - 7*3, MATLAB returns ans = 104.1000. Then sqrt(ans) produces ans = 10.2029.
Users can also assign values to custom variables of their own choice. For example, to compute sin²(1) + cos²(1):
a = cos(1)assignsa = 0.5403b = sin(1)assignsb = 0.8415a^2 + b^2returnsans = 1
💡 Why this matters: Understanding the ans variable and custom variable assignment is crucial for building multi-step calculations efficiently without retyping values.
Symbolic Computation
For exact symbolic calculations, the Symbolic Math Toolbox must be installed. To verify installation, type help symbolic in the Command Window. To perform symbolic computations, use the syms command to declare variables as symbolic.
🔑 Definition — syms: A command used to declare symbolic variables for exact algebraic computation
📌 Example: syms x y declares x and y as symbolic variables. Then (x-y)*(x-y)^2 returns the symbolic expression (x-y)^3. Additional commands like expand(ans) expand the expression, and factor(ans) factors it.
🔑 Definition — sym: A command that provides exact (symbolic) values rather than floating-point approximations
📌 Example: cos(sym('pi/2')) returns 0 exactly, while cos(pi/2) returns 6.1232e-17 due to floating-point approximation. Similarly, sym('1/2') + sym('1/3') returns 5/6 exactly.
💡 Why this matters: MATLAB normally uses floating point arithmetic, which can produce small rounding errors. The sym command provides exact arithmetic, which is essential for precise mathematical work.
Substitution in Symbolic Expressions
The subs command substitutes numerical values or other symbolic expressions for variables in symbolic expressions.
🔑 Definition — subs: A command used to substitute a value or expression for a symbolic variable
📐 Formula: subs(expression, old_variable, new_value) → Replaces the old variable with the new value in the expression
📌 Example: Given u = x + y^2:
subs(u, x, 2)substitutes 2 for x, givingans = y^2 + 2subs(u, y, y+x)substitutes (y+x) for y, givingans = x + (x + y)^2
Errors in input
If an incorrect command is entered, MATLAB beeps and displays an error message. Common errors include omitting parentheses or misspelling function names.
🔑 Definition — Common input error: An incorrectly formatted command that MATLAB cannot interpret
📌 Example: Typing sin10 produces the error: ??? Undefined function or variable 'sin10'. The correct command is sin(10), which returns ans = -0.5440.
💡 Why this matters: Recognizing and correcting input errors saves time and ensures accurate calculations. All MATLAB functions require parentheses around their arguments.
⭐ Key Takeaways
Students must remember that MATLAB uses the ans variable to store each calculation result, but custom variables can be assigned for complex computations. The syms command is essential for creating symbolic variables for exact algebraic manipulations, while the sym command provides exact arithmetic to avoid floating-point errors. The subs command allows flexible substitution of numerical values or symbolic expressions into symbolic expressions. Finally, all MATLAB functions require proper syntax with parentheses, and incorrect formatting will generate error messages that must be corrected by using the proper command structure.
🧠 Quick Revision Questions
- What command would you use to compute the exact (symbolic) sum of 1/7 and 1/8?
- How do you substitute the value 5 for the variable z in the symbolic expression w = z^2 + 3z?
- What is the ans variable in MATLAB and when is it updated?
- What is the correct MATLAB syntax to compute the sine of 45 degrees?
- Why does
cos(pi/2)give 6.1232e-17 instead of 0, and how can you obtain the exact result?
📘 Lecture 3 — Doing Mathematics with MATLAB II
📖 Overview: This lecture continues the study of MATLAB as a computational tool, focusing on practical methods for performing mathematics. It covers variable assignment, vector creation and manipulation, the use of built-in and user-defined functions, and techniques for solving algebraic equations. Mastering these skills is essential for efficiently using MATLAB in mathematical problem-solving.
🗂️ Topics Covered
The lecture begins with Variables and Assignments in MATLAB, explaining how to assign and clear values. It then covers Vectors, including creation, row/column conversion, element extraction, and mathematical operations. Next, it introduces Built-in Functions like exp, log, and sqrt. The User Defined Functions section explains how to create custom functions using the @ operator for single and multivariable expressions. Finally, Solving Algebraic Equations is addressed using the solve and fzero commands for single equations, systems, and numerical solutions.
📝 Lecture Summary
Variables and Assignments
In MATLAB, the = sign is used to assign a value to a variable. For example, typing x=7 assigns the value 7 to the variable x. Once assigned, MATLAB substitutes that value whenever x is used in an expression. For instance, if y is a symbolic variable, x^3 + 2*x*y + 10*x with x=7 evaluates to 14*y + 413.
To assign a new value to a variable x, you must first clear the old value using the clear x command. For example, after typing clear x, you can type x=8, and then the expression x^3 + 2*x*y + 10*x evaluates to 16*y + 592.
🔑 Definition — Variable Assignment: The process of using the = sign to store a specific numerical or symbolic value in a variable name for later use.
📐 Formula: variable_name = value → The variable on the left is assigned the value on the right.
📌 Example: Type x=7 in the Command Window. Then type x^2. MATLAB returns ans = 49 because x has been assigned the value 7. To change x to 8, type clear x, then x=8.
Vectors
A vector is an ordered list of numbers. In MATLAB, a vector is entered by typing a list of numbers, separated by commas or spaces, inside square brackets ([]). For example, X=[2,4,5] creates a row vector with entries 2, 4, and 5. Similarly, Y=[2,7,8] creates a row vector Y.
A vector can also be created using the colon operator (:) to generate a sequence. The notation X=2:5 creates a vector [2,3,4,5], running from 2 to 5 with an increment of 1. You can specify a custom increment as the second of three arguments: Y=1:2:12 creates [1,3,5,7,9,11].
To transpose a row vector into a column vector, place a prime (') after the variable name. For example, Y' returns a column vector of the elements. You can also extract individual entries using parentheses: Y(3) returns the third element of Y, which is 5.
Mathematical operations can be performed on vectors element-by-element using a dot operator (.). For example, to square each element of Y, use Y.^2, which returns [1, 9, 25, 49, 81, 121]. Other operations include element-wise multiplication (Y.*Y) and element-wise division (Y./3).
🔑 Definition — Dot Operator: A period placed before an arithmetic operator (.*, ./, .^) in MATLAB to indicate that the operation should be performed element-by-element on arrays.
📐 Formula: vector.^2 → squares every element of the vector.
📌 Example: If Y=[1,3,5], then Y.^2 results in [1,9,25]. Y.*Y also results in [1,9,25]. Y./2 results in [0.5, 1.5, 2.5].
Built-in Functions
MATLAB has all the usual elementary functions built in. These functions operate on scalars and vectors. For example, exp(x) returns the exponential function of x (e^x). log(x) returns the natural logarithm of x. The sqrt(x) command is used to take the square root of x.
🔑 Definition — Elementary Functions: Pre-defined mathematical functions available in MATLAB, such as exp, log, and sqrt.
User Defined Functions
Users can define their own custom functions in MATLAB. The preferred method is using the @ operator (function handle). For example, to define the function f(x) = x^3, type f = @(x)x^3. The variable f now represents the function.
Once defined, the function can be evaluated at any real number. For example, f(10) returns 1000, and f(9) returns 729.
This method can also define functions of several variables. For example, h = @(x,y)x^2+y^2 defines the function h(x,y) = x^2 + y^2. It can be evaluated at specific values: h(1,2) returns 5.
🔑 Definition — Function Handle (@): A MATLAB data type that stores a reference to a function, allowing it to be called indirectly or passed as an argument. It is created using the @ operator.
📐 Formula: function_name = @(input_variables) expression → Creates a user-defined function.
📌 Example: Type f = @(x)x^3. Then type f(2). MATLAB returns ans = 8. Type h = @(x,y)x^2+y^2. Then type h(3,4). MATLAB returns ans = 25.
Solving Algebraic Equations
MATLAB can solve algebraic equations using the solve command. The equation to be solved can be specified as a string (surrounded by single quotes). For example, to solve x^2 - 5*x + 6 = 0, type solve('x^2-5*x+6=0'). The output is ans = 2 and ans = 3.
Alternatively, the input to solve can be a symbolic expression. First, declare the variable as symbolic: syms x. Then, type solve(x^2 - 3*x + 7). This solves x^2 - 3*x + 7 = 0 and returns complex solutions: 3/2 - (19^(1/2)*i)/2 and 3/2 + (19^(1/2)*i)/2.
The solve command can handle systems of equations. To solve x^2 - y = 2 and y - 2*x = 5, use [x,y] = solve('x^2-y=2', 'y-2*x=5'). MATLAB returns two x-values and two y-values corresponding to two solutions. The first solution can be extracted using x(1) and y(1).
Sometimes, an equation has multiple solutions, and solve may not return the one you expect. For example, solve('exp(-x) = sin(x)') might give a complex number. To find a specific numerical solution, use the fzero command. First, define a function handle for h(x) = exp(-x) - sin(x): h = @(x)exp(-x)-sin(x);. Then, use fzero(h, 0.5) to find a root near 0.5. The output is ans = 0.5885.
🔑 Definition — solve: A symbolic math function in MATLAB used to find exact solutions to algebraic equations.
🔑 Definition — fzero: A numerical function in MATLAB that finds the root of a continuous function near a specified starting point.
📐 Formula: solve('equation=0') → finds exact symbolic solutions. fzero(function_handle, initial_guess) → finds a numerical root near the guess.
📌 Example 1 (solve): Type solve('x^2-5*x+6=0'). Output: 2, 3. Type [x,y] = solve('x^2-y=2', 'y-2*x=5'). Output: x = 2*2^(1/2)+1, 1-2*2^(1/2), y = 4*2^(1/2)+7, 7-4*2^(1/2).
📌 Example 2 (fzero): Type h = @(x)exp(-x)-sin(x); then fzero(h, 0.5). Output: 0.5885.
💡 Why this matters: The solve and fzero commands are essential tools for finding both exact symbolic and approximate numerical solutions to equations, a fundamental task in all areas of mathematics and engineering.
⭐ Key Takeaways
The most critical concepts from this lecture are understanding how to assign and clear variable values, create vectors using the colon operator and perform element-wise operations using the dot operator, and define custom functions with the @ operator. For solving equations, you must know how to use solve for exact symbolic solutions of single and system equations, and fzero for finding a specific numerical root near a starting guess. Remember that element-wise operations require a dot before the operator, and that the input to solve can be a string or a symbolic expression. For multiple solutions, individual elements can be extracted using parentheses indexing.
🧠 Quick Revision Questions
- What command is used in MATLAB to remove the value assigned to a variable so a new value can be assigned?
- How would you create a row vector containing the numbers 10, 20, 30, and 40 in MATLAB?
- If
Y = [2, 4, 6], what is the result of the MATLAB commandY.^2? - Write the MATLAB command to define a user-defined function
g(x,y) = x^2 + y^3. - What is the difference between using
solve('x^2-2=0')and usingfzero(@(x)x^2-2, 1)to solve the equation?
📘 Lecture 4 — Graphics Techniques in MATLAB
📖 Overview: This lecture introduces the fundamental plotting commands in MATLAB, focusing on how to visualize mathematical functions and data. It covers the
ezplotcommand for symbolic and anonymous functions, theplotcommand for numerical data, and techniques for modifying graphs, plotting multiple curves, creating parametric plots, and generating contour plots.
🗂️ Topics Covered
The lecture covers the ezplot command with symbolic expressions and anonymous functions, modification of graphs using labels, titles, and grids, the plot command for vector data, graphing multiple curves using hold on/hold off, parametric plots of a circle, and contour plots using meshgrid and contour commands. Each topic includes examples and step-by-step solutions.
📝 Lecture Summary
Graphics Techniques in MATLAB
ezplot Command
The ezplot command is used to plot the graph of a function of one variable. It accepts a string, a symbolic expression, or a function handle (anonymous function) representing the function to be plotted. For example, to draw the graph of the function x^3 on the interval [-2,2] using the string form, the command is ezplot('x^3',[-2,2]). The result displays in a new window labeled "Figure 1".
ezplot command with symbolic expression
The ezplot command can also accept a symbolic expression. To use this form, first declare a symbolic variable using syms x, then call ezplot(x^3, [-2,2]). This produces the same graph as the string form but uses a variable that has been symbolically defined. This method is useful when working with symbolic mathematics in MATLAB.
ezplot command on anonymous function
The graph of a function can also be plotted using an anonymous function as the argument of ezplot. For example, ezplot(@(x)x.^3, [-2,2]) produces the same plot. The anonymous function is defined using the @(x) syntax, and the element-wise power operator .^ is used. This approach is flexible and avoids needing to define symbolic variables.
Modification of Graphs
Graphs can be modified in a number of ways. The title of the graph can be inserted using the title command. Different types of labels can be given to both axes using xlabel and ylabel. The region of the graph can be displayed with a grid using the grid command. To accomplish this, type the commands syms x y; y=ezplot(x^3, [-2,2]); xlabel('x'); ylabel('y'); title('The graph of y=x^3'); grid;. This sequence adds a title, axis labels, and grid lines to the plot.
Example
Example: Plot the graph of the function y=x^2 on [-3,3] using the ezplot command, considering x and y to be symbolic variables. Label the horizontal axis as "VU" and vertical axis as "IT". Keep the title of the graph as "Parabola".
Solution: The following syntax can be used: syms x y; y=ezplot(x^2, [-3,3]); xlabel('VU'); ylabel('IT'); title('Parabola'); grid;.
Plot command
The plot command works on vectors of numerical data. The syntax is plot(X,Y), where X and Y are vectors of the same length. This command considers the vectors X and Y to be lists of x and y coordinates of successive points on a graph, and joins the points with lines. For example, the vectors X = [3 5 7] and Y = [9 11 13] are connected by line segments as (3,9) to (5,11) to (7,13).
Example: Using the plot command, plot the graph of x^2 + x + 1 on the interval [-2,2] by taking an increment of 0.1 for the domain set. Label the horizontal axis with x and vertical axis with y. Finally, give the title "Parabola" to the graph.
Solution: First, make a list X of x values: X = -2:0.1:2;. Then, plot using plot(X, X.^2 + X + 1). Add labels and grid: xlabel('x'); ylabel('y'); title('Parabola'); grid;.
Graphs of Multiple Curves
Each time a plotting command is executed, MATLAB erases the old plot and draws a new one. To see two or more plots together, use the command hold on. This command instructs MATLAB to retain the old graphics and draw any new graphics on top of the old. This command remains in effect until hold off is typed.
Example: Plot the graphs of e^{-x} and sin(x) on the interval [0,8] using the ezplot, hold on, and hold off commands. Label the horizontal axis with x and vertical axis with y. Give the title "Multiple Graphs".
Solution using ezplot: syms x; ezplot(exp(-x),[0,8]); hold on; ezplot(sin(x),[0,8]); hold off; title('Multiple Graphs'); xlabel('x'); ylabel('y'); grid;.
Solution using plot: X = 0:0.1:8; plot(X,exp(-X)); hold on; plot(X,sin(X)); hold off; title('Multiple Graphs'); xlabel('x'); ylabel('y'); grid;.
Parametric Plots
The flexibility of the plot command is demonstrated by the parametric plot of a circle centered at (0,0) with radius 1. The parametric representation is x = cos(2πt) and y = sin(2πt), where t varies from 0 to 1. The recipe for graphing parametric plots is:
t = 0:0.1:1;
plot(cos(2*pi*t), sin(2*pi*t));
xlabel('x');
ylabel('y');
title('Parametric plot of circle');
grid;
axis square;
📌 Example: Plot the parametric graph of the circle with center at (0,0), radius 1, and with an increment of 0.01 in the domain set. Label the axes and keep the title "Parametric plot of the circle".
Solution: Use t = 0:0.01:1; and then plot(cos(2*pi*t), sin(2*pi*t)); xlabel('x'); ylabel('y'); title('Parametric plot of circle'); grid; axis square;.
Contour Plot
A contour plot of an expression in two variables is a plot of the level curves of that expression. For example, the level curves of x^2 + y^2 are circles. The meshgrid and contour commands are used for contour plotting. The meshgrid command produces a grid of points in a specified rectangular region with a specified spacing. The contour command produces the contour plots in the specified regions.
Example: Plot the contour plots of the expression x^2 + y^2 using meshgrid and contour commands. Label the axes, make the shape square, and give the title "Contour plotting of squares".
Solution: [X,Y] = meshgrid(-2:0.1:2, -2:0.1:2); contour(X,Y,X.^2+Y.^2); axis square; xlabel('x'); ylabel('y'); grid; title('Contour plotting of squares');.
⭐ Key Takeaways
The ezplot command is straightforward for symbolic or anonymous functions, while the plot command is used for numerical vector data and requires generating x- and y-value arrays. Graphs can be enhanced using xlabel, ylabel, title, and grid commands. To overlay multiple plots, use hold on followed by hold off. Parametric plots elegantly represent curves like circles using trigonometric functions, and contour plots with meshgrid and contour visualize level curves of two-variable functions.
🧠 Quick Revision Questions
- What are the three different forms of input that the
ezplotcommand can accept? - What is the purpose of the
hold oncommand when plotting multiple curves in MATLAB? - For the
plotcommand, how are the vectorsXandYinterpreted, and what is a key requirement for them? - Write the MATLAB code to plot a parametric circle of radius 1 using a
tvector from 0 to 1 with step 0.01. - What is the role of the
meshgridcommand in creating a contour plot?
📘 Lecture 5 — Ezplot, Plot and FPlot
📖 Overview: This lecture explores the different plotting commands available in MATLAB for creating 2-D and 3-D visualizations. Understanding the distinctions between ezplot, plot, fplot, and their 3-D counterparts (fsurf, fmesh, fplot3) is crucial for effectively presenting mathematical functions and data in engineering and scientific computing.
🗂️ Topics Covered
The lecture begins with the ezplot command for plotting explicit functions over default or specified domains, then moves to the more versatile plot command for line plots with customizable line styles, markers, and colors. Next, fplot is introduced as a function plotting tool with parametric capabilities, followed by fplot3 for 3-D parametric curves. The lecture concludes with fsurf for surface plots and fmesh for mesh plots, including parametric surface visualization.
📝 Lecture Summary
ezplot Command
The ezplot command provides a quick way to plot explicit functions of one or two variables with minimal syntax. ezplot(fun) plots the expression fun(x) over the default domain -2π < x < 2π for functions of x only. For implicit functions of two variables like x^2 - y^4 = 0, ezplot automatically handles the relationship. Functions can be passed as character vectors, strings, or function handles.
🔑 Definition — ezplot: A MATLAB command that plots symbolic expressions or functions without requiring explicit data point generation.
📐 Syntax forms:
ezplot(fun)→ plots over default domain [-2π, 2π]ezplot(fun,[xmin,xmax])→ specifies x-domainezplot(funx,funy)→ parametric form
📌 Example:
ezplot('x^2') % Plots parabola over [-2π, 2π]
ezplot('x^2-y^4') % Plots implicit function
fh= @(x,y) x.^2 + y.^3 -2*y - 1; % Function handle
ezplot(fh) % Plots implicit function defined by handle
plot Command
The plot function creates 2-D line plots of data arrays. plot(X,Y) creates a line plot of Y versus X. It supports multiple line specifications including LineSpec for controlling line style, marker symbol, and color. Multiple data sets can be plotted on the same axes by providing X,Y pairs.
🔑 Definition — LineSpec: A character string that defines line style, marker type, and color for a plot (e.g., '--' for dashed line, 'o' for circle marker, 'r' for red).
📐 Syntax:
plot(X,Y)→ basic line plotplot(X,Y,LineSpec)→ with style specificationsplot(X1,Y1,...,Xn,Yn)→ multiple data sets
💡 Why this matters: The plot command is the fundamental visualization tool in MATLAB for displaying numerical data, making it essential for data analysis and presentation.
📌 Example:
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y) % Basic sine plot
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
plot(x,y1,x,y2) % Multiple lines
Y = magic(4) % 4x4 magic square
plot(Y) % Plots each column as separate line
Specify Line Style, Color, and Marker
Line styles include solid (-), dashed (--), dotted (:), and dash-dot (-.). Markers add visual emphasis at data points: circle ('o'), plus sign ('+'), asterisk ('*'), point ('.'), cross ('x'), square ('s'), diamond ('d'), triangles ('^', 'v', '>', '<'), pentagram ('p'), hexagram ('h'). Colors: yellow (y), magenta (m), cyan (c), red (r), green (g), blue (b), white (w).
📌 Example:
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
figure
plot(x,y1,x,y2,'--',x,y3,':') % Solid, dashed, dotted styles
x = linspace(0,10);
y = sin(x);
plot(x,y,'-o','MarkerIndices',1:5:length(y)) % Every 5th point marked with circle
fplot Command
fplot plots expressions or functions with automatic sampling, handling discontinuities better than plot. fplot(f) plots y = f(x) over default interval [-5 5]. It supports parametric curves via fplot(funx,funy) and piecewise functions with hold on/off. LineSpec works the same as in plot.
🔑 Definition — fplot: A command that plots function handles with adaptive sampling, handling discontinuities automatically.
📐 Syntax:
fplot(f)→ plots function over [-5 5]fplot(f,[xmin xmax])→ specified intervalfplot(funx,funy)→ parametric curvefplot(funx,funy,[tmin tmax])→ parametric with interval
📌 Example:
fplot(@(x) sin(x)) % Sine over [-5 5]
% Parametric curve
xt= @(t) cos(3*t);
yt= @(t) sin(2*t);
fplot(xt,yt) % Lissajous curve
% Multiple lines with different styles
fplot(@(x) sin(x+pi/5),'Linewidth',2);
hold on
fplot(@(x) sin(x-pi/5),'--or');
fplot(@(x) sin(x),'-.*c')
hold off
fplot3 Command
fplot3 creates 3-D parametric curve plots. It takes three function handles for x(t), y(t), z(t) over default interval [-5 5] for t. Supports custom intervals, LineSpec, and Name-Value properties.
📐 Syntax:
fplot3(funx,funy,funz)→ basic 3-D parametricfplot3(funx,funy,funz,tinterval)→ specified rangefplot3(___,LineSpec)→ with style
📌 Example:
% Helix over default range [-5 5]
xt= @(t) sin(t);
yt= @(t) cos(t);
zt= @(t) t;
fplot3(xt,yt,zt)
% Spiral with exponential decay
xt= @(t) exp(-t/10).*sin(5*t);
yt= @(t) exp(-t/10).*cos(5*t);
zt= @(t) t;
fplot3(xt,yt,zt,[-10 10])
% Multiple segments with different styles
fplot3(@(t)sin(t), @(t)cos(t), @(t)t, [0 2*pi], 'LineWidth', 2)
hold on
fplot3(@(t)sin(t), @(t)cos(t), @(t)t, [2*pi 4*pi], '--or')
fplot3(@(t)sin(t), @(t)cos(t), @(t)t, [4*pi 6*pi], '-.*c')
hold off
fsurf Command
fsurf creates surface plots of functions z = f(x,y) over default interval [-5 5] for x and y. Supports parametric surfaces via fsurf(funx,funy,funz) where x, y, z are functions of u and v. Can plot piecewise expressions over different intervals.
📐 Syntax:
fsurf(f)→ surface of z = f(x,y)fsurf(f,xyinterval)→ specified [xmin xmax ymin ymax]fsurf(funx,funy,funz)→ parametric surfacefsurf(funx,funy,funz,uvinterval)→ parametric with interval
📌 Example:
% Basic surface
fsurf(@(x,y) sin(x)+cos(y))
% Piecewise surface
f1 = @(x,y) erf(x)+cos(y);
fsurf(f1,[-5 0 -5 5])
hold on
f2 = @(x,y) sin(x)+cos(y);
fsurf(f2,[0 5 -5 5])
hold off
% Parameterized surface with camlight
r = @(u,v) 2 + sin(7.*u + 5.*v);
funx= @(u,v) r(u,v).*cos(u).*sin(v);
funy= @(u,v) r(u,v).*sin(u).*sin(v);
funz= @(u,v) r(u,v).*cos(v);
fsurf(funx,funy,funz,[0 2*pi 0 pi])
camlight
fmesh Command
fmesh creates mesh plots of functions z = f(x,y) over default interval [-5 5] for x and y. Similar to fsurf but shows a wireframe mesh instead of a solid surface. Supports parametric meshes and transparency via alpha.
📐 Syntax:
fmesh(f)→ mesh of z = f(x,y)fmesh(f,xyinterval)→ specified domainfmesh(funx,funy,funz)→ parametric meshfmesh(funx,funy,funz,uvinterval)→ parametric with interval
📌 Example:
% Basic mesh
fmesh(@(x,y) sin(x)+cos(y))
% Parameterized mesh with transparency
r = @(s,t) 2 + sin(7.*s + 5.*t);
x = @(s,t) r(s,t).*cos(s).*sin(t);
y = @(s,t) r(s,t).*sin(s).*sin(t);
z = @(s,t) r(s,t).*cos(t);
fmesh(x,y,z,[0 2*pi 0 pi])
⭐ Key Takeaways
The distinction between ezplot (quick symbolic plots), plot (data-driven line plots with full customization), and fplot (adaptive function plotting) is fundamental for choosing the right tool. LineSpec strings combine line style, marker, and color into a single string (e.g., '--or' for dashed red line with circle markers). For 3-D visualization, fplot3 handles parametric curves while fsurf and fmesh create surfaces and meshes respectively. Parametric plotting is a powerful feature shared by fplot, fplot3, fsurf, and fmesh, enabling complex geometries. Remember that hold on/off allows overlaying multiple plots in the same figure, and camlight adds realistic lighting to surfaces.
🧠 Quick Revision Questions
- What is the default domain for ezplot when plotting a function of one variable?
- How would you plot a dashed red line with circle markers every 5th data point using the plot command?
- What is the key difference between fplot and plot regarding how they handle discontinuities?
- Write the MATLAB code to plot the parametric curve x = sin(3t), y = cos(2t) for t from 0 to 2π.
- What command would create a mesh plot of z = x² + y² over the interval [-3,3] for both x and y?
📘 Lecture 7 — Solve Differential Equation with Condition
📖 Overview: This lecture demonstrates how to solve ordinary differential equations (ODEs) with specified initial conditions using MATLAB's
dsolvefunction. It shows the crucial difference between general solutions (with arbitrary constants) and particular solutions (with constants determined by conditions). A step-by-step example illustrates the complete process.
🗂️ Topics Covered
The lecture covers solving differential equations with initial conditions in MATLAB, the role of the dsolve function with conditions, and a concrete example solving the ODE dy/dt + 4y(t) = e^(-t) with y(0) = 1. It emphasizes how specifying a condition eliminates the arbitrary constant to produce a unique solution.
📝 Lecture Summary
Solve Differential Equation with Condition
In the previous solution, the constant C appears because no condition was specified. To obtain a unique solution, you must provide an initial condition that allows MATLAB to determine the value of C. The dsolve function finds a value of C that satisfies the condition.
🔑 Definition — Initial condition: A specified value of the dependent variable at a particular point (usually t=0) that determines the arbitrary constant in the general solution.
💡 Why this matters: Without initial conditions, you get a family of solutions (general solution). With conditions, you get one specific solution that matches real-world behavior.
Example: dy/dt + 4y(t) = e^(-t), y(0) = 1
This example demonstrates the complete process of solving an ODE with an initial condition.
Step-by-step MATLAB implementation:
-
Declare the symbolic variable and function:
syms y(t) -
Define the ODE:
ode = diff(y) + 4*y == exp(-t); -
Specify the initial condition:
cond = y(0) == 1; -
Solve with the condition:
ySol(t) = dsolve(ode, cond)
📐 Formula (General Solution): The differential equation has the form dy/dt + 4y = e^(-t)
📌 Example with full context:
- Given: ODE: dy/dt + 4y(t) = e^(-t), with y(0) = 1
- MATLAB command:
ySol(t) = dsolve(ode, cond) - Result: The solution ySol(t) is the particular function that satisfies both the differential equation and the initial condition y(0) = 1
- Key observation: Without
cond, the solution would include an arbitrary constant C. Withcond, MATLAB computes the specific value of C that makes y(0) = 1
⭐ Key Takeaways
The most critical takeaway is that initial conditions are essential for obtaining unique solutions to differential equations — without them, you only get a general solution family. The dsolve function in MATLAB automatically handles this when you pass the condition as a second argument. The example shows the complete workflow: define symbolic variables, write the ODE, specify the condition using ==, and call dsolve with both. A common mistake is forgetting to use syms y(t) before defining the ODE. Remember that conditions use == (logical equality), not assignment (=).
🧠 Quick Revision Questions
- What is the purpose of adding an initial condition when solving an ODE?
- In the example, what is the correct syntax for defining a condition where y(0) equals 1?
- How does the solution differ when you use
dsolve(ode)versusdsolve(ode, cond)? - Why must you declare
syms y(t)before defining the ODE in MATLAB? - What type of mathematical object does
dsolvereturn when a condition is provided?
📘 Lecture 8 — Nonlinear Differential Equation with Initial Condition
📖 Overview: This lecture demonstrates how to solve nonlinear and second-order differential equations with initial conditions using MATLAB's Symbolic Math Toolbox. Multiple examples show the
dsolvefunction for handling various ODE types, including nonlinear equations, second-order ODEs, and Cauchy-Euler equations.
🗂️ Topics Covered
Solving a nonlinear first-order differential equation with initial condition that yields multiple solutions, solving a second-order ODE with two initial conditions using symbolic differentiation, solving a second-order Cauchy-Euler equation without initial conditions, and using simplify to clean solution expressions.
📝 Lecture Summary
Nonlinear Differential Equation with Initial Condition
We solve a nonlinear differential equation with an initial condition where the equation has multiple solutions. The equation is (dy/dt + y)² = 1 with y(0) = 0. Using MATLAB's dsolve function with symbolic variables, the code produces solutions that account for the nonlinearity.
📌 Example: For the ODE (dy/dt + y)² = 1 with y(0) = 0, the MATLAB code is:
syms y(t)
ode = (diff(y,t)+y)^2 == 1;
cond = y(0) == 0;
ySol(t) = dsolve(ode,cond)
Second-Order ODE with Initial Conditions
We solve a second-order differential equation with two initial conditions. The equation is d²y/dx² = cos(2x) - y with y(0) = 1 and y'(0) = 0. We first define Dy = diff(y) to represent the first derivative, then set up the ODE and conditions as arrays using square brackets. The simplify function cleans the final solution.
📌 Example: For the ODE d²y/dx² = cos(2x) - y:
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 — Second-Order Cauchy-Euler Equation
We solve a Cauchy-Euler equation: 2x²(d²y/dx²) + 3x(dy/dx) - y = 0. This is a homogeneous second-order linear ODE with variable coefficients. No initial conditions are provided, so the solution contains arbitrary constants.
📌 Example: For the Cauchy-Euler equation:
syms y(x)
ode = 2*x^2*diff(y,x,2)+3*x*diff(y,x)-y == 0;
ySol(x) = dsolve(ode)
⭐ Key Takeaways
For solving differential equations in MATLAB, always define the dependent variable as a symbolic function of the independent variable using syms. Use diff(y,x,2) for second derivatives and Dy = diff(y) for first derivatives when setting initial conditions. Store multiple initial conditions in an array [cond1 cond2] and pass them to dsolve. For nonlinear equations, expect multiple solutions. Use simplify(ySol) to clean up complex symbolic expressions.
🧠 Quick Revision Questions
- What MATLAB function is used to solve differential equations symbolically?
- How do you represent a second derivative in MATLAB's Symbolic Math Toolbox?
- How should you format multiple initial conditions when passing them to
dsolve? - What type of equation is
2x²y'' + 3xy' - y = 0called? - What happens when you solve a differential equation with no initial conditions?
📘 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?
📘 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?