๐ 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?