Matlab introductory course part 4 with the following agenda: Creating M files, User-Defined Functions, Solving Linear Equations, Symbolic Algebra, and Calculus
4. MATLAB Environment
There are two ways to work with
MATLAB.
■ Command Window
• For small tasks or simple
calculations
• Will execute as soon as you press
Enter key
• Interactive ;as each command is
entered , a response is returned
■ M- files
• For large programs
• Known as m-files because of
their .m extension.
• Usually used when having user
defined functions.
5. Matlab M-files
■ To create M-files :
• File > New > Script
• Or use the shortcut ctrl +N
• Or from the toolbar , by clicking on the
icon called “New Script”
■ Running m- file:
• >>filename
• >>run filename
• >> run (‘filename’)
6. Saving your work
Using Diary
■ Another way of saving a segment
of code or calculations using
the diary.
• >> diary on
• code
• >>diary off
• Or >> diary (‘filename’)
A file has
been
created
with the
variables
saved in
it.
7. Saving your work
■ After finishing code
instructions type the command
save .
■ It will create a file with
variables stored in it
• >> save filename
It saves the variables in
the work spaces and
allow to overwrite them
8. Cell Mode
■ Cell mode is a utility that allows you to divide M-
files into sections, or cells.
■ Each cell can be executed one at a time.
• From tab Cell >> Evaluate Current Cell
• Or ctrl + Enter
■ To divide M-file ,use
%% cell name
■ We can use the icons on the tool strip to evaluate a
single section.
■ To navigate between cells.
• From tab GO >> Go To
• Or ctrl + G
Dividing m-
file into cells
9. Formatting Results
• The format command controls
how tightly information is
spaced in the command
window.
• For example we took pi as an
number to represent different
formats
Command Display Example
format short 4 decimals 3.1416
format long 14 decimals 3.141592653589793
format short e 4 decimals in
scientific
3.1416e+000
format long e 14 decimals in
scientific
3.141592653589793e+000
format bank 2 decimals 3.14
format short eng 4 decimals in
engineering
3.1416e+000
format long eng 14 decimals in
engineering
3.14159265358979e+000
format + +, - , bank +
format rat Fractional form 355/113
format short g Matlab selects
the best format
3.1416
format long g Matlab selects
the best format
3.14159265358979
11. User Defined Functions
■ Function: is a piece of
computer code that accepts an
input argument from the user
and provides output to the
program.
■ Functions allows us to program
efficiently.
• Creating functions is done
using M-files.
■ Function Definition:
1. The word ‘function’
2. A variable that defines the function
output
3. A function name
4. A variable used for the input argument
1 2 3 4
12. Defining a Function
■ To create a function , an M-file
must be created in the current
folder of the project and it
should have the same name as
the function .
13. Practice:
■ Create MATLAB functions to evaluate the following
mathematical functions.
• y(x) = 𝑥2
• y(x) = 𝑒 Τ
1
𝑥
• y(x) = sin(𝑥2
)
Hint:
To test your
function, you have
to call it from the
command window
14. Functions with Multiple Inputs and
Outputs
■ Multiple Inputs :
• For example ‘rem(x,y)’ takes two
inputs.
■ Similarly , a user defined function
could have multiple inputs.
• X and Y can be either scalars or
vectors.
■ Multiple Outputs:
• A function could return more
than one output. [output1 ,output2,…..]
If you call the
function without
specifying all the
three outputs ,
only the first one
is shown
15. Practice:
■ Assuming that the matrix dimensions agree, create and test
MATLAB functions to evaluate the following simplest
mathematical functions:
• 𝑧 𝑥, 𝑦 = 𝑥 + 𝑦
• 𝑧 𝑎, 𝑏, 𝑐 = 𝑎𝑏𝑐
• 𝑓 𝑥 = 5𝑥2
+ 2
• 𝑓 𝑥, 𝑦 = 𝑥 + 𝑦
• 𝑓 𝑥, 𝑦 = 𝑥𝑒𝑦
• 𝑓 𝑥 = 5𝑥2 + 2
16. Functions with No Inputs or
Outputs
■ Consider the following
function:
■ The square brackets indicates
an empty output function.
■ The parentheses indicates an
empty input function.
■ nargin() A function determines the
number of the input arguments in either a
user-defined function or a built-in
function.
■ nargout() A function determines the
number of the output arguments in either a
user-defined function or a built-in
function.
From the command window
-1
indicates
a
variable
of No
inputs
17. Local Variables
■ A local variable : is a variable
only accessed in its scope.
■ The variables used in functions
M-files are local variables.
■ Any variables defined within a
function exist only for that
function to use.
■ No local variables in a function
exist in the workspace.
g is not there
18. Global Variables
■ A global variable : is accessed
for all parts of a computer
program.
■ To use a global variable:
• Use the command ‘global var1’
■ It should be defined in the
command window or in a script
file
■ The global command alerts the
function to look in the
workspace for the value G.
■ This approach allows you to
change the value of G without
needing to redefine the
function in the M-file.
19. Accessing M-Files Code
■ The functions provided with
MATLAB are two types.
• Built in: its code is not
accessible.
• M-files stored in toolboxes
provided with the program.
■ We can see these M-files (or the
M-files we have written).
■ For example ,the sphere function
creates a three dimensional
shape.
■ Returns the contents of the
function you have defined earlier.
Try this:
20. Subfunctions:
■ More complicated functions can be
created together in a single file as
subfunctions.
■ Each MATLAB function M-file
has one primary function. The
name of the M-file must be the
same as the name of the primary
function name.
■ Subfunctions are added after
the primary function and can
have any variable name.
■ We use the ‘end’command to
indicate the end of each
individual function. This called
nesting.
Nesting : is when
the primary
function and other
subfunctions are
listed
sequentially.
22. Polynomials
■ In MATLAB, a polynomial is
represented by a vector
■ To create a polynomial in
MATLAB, simply enter each
coefficient of the polynomial into
the vector in descending order.
■ For instance:
𝑥4
+ 3𝑥3
− 15𝑥2
− 2𝑥 + 9 , it can be
entered as a vector X = [ 1 ,3 ,-15 ,-2,9]
■ If it is missing any coefficients
, you must replace them by
entering zeros in the
appropriate place in the vector
• For example, 𝑥4
+ 1 it is saved
like this: Y = [ 1,0,0,0,1]
23. Polynomials
■ To find the value of the polynomial
y= 𝑥4
+ 1 at x =2
• Use the command:
• Z = polyval([1 0 0 0 1],2)
OR
• Z = polyval(y,2)
■ To extract the roots of a polynomial
such as : 𝑥2
− 5𝑥 + 6
• Use the command:
• Roots([1,-5 ,6])
24. System of Linear
Equations
■ Consider the following linear equations:
• 3x +2y –z = 10
• -x + 3y +2z = 5
• x –y – z = -1
• 𝐴 =
3 2 1
−1 3 2
1 −1 −1
𝑥
𝑦
𝑧
=
10
5
−1
1. Using the inverse:
25. System of Linear Equations
2. Using Gaussian elimination:
• Try this:
■ Consider the following equations:
• 3x +2y +5z = 22
• 4x + 5y -2z = 8
• x +y + z = 6
𝐴 =
3 2 5
4 5 −2
1 1 1
𝑥
𝑦
𝑧
=
22
8
6
26. System of Linear
Equations
3. Using the reverse row Echelon function:
■ Consider the following equations:
• 3x +2y -2z = 10
• -x + 3y +2z = 5
• x -y - z = -1
𝐴 =
3 2 1
−1 3 2
1 −1 −1
𝑥
𝑦
𝑧
=
10
5
−1
Solution of x ,y ,z
28. Symbolic Algebra
■ It is preferable to manipulate
the equations symbolically
before substituting values for
variables.
■ MATLAB ‘s symbolic algebra
capabilities allow you to
perform substituting ,
simplification , factorization,
..etc.
■ Creating symbolic variables:
• New variable:
• In the workspace:
or
They are in the
form of arrays
29. Practice:
■ You can declare multiple
symbolic at the same time.
■ Notice that:
■ Create the following symbolic variables, using
sym or syms command :
x, a ,b, c, d
■ Use the symbolic variables you created for the
following expressions:
• ex1 = 𝑎𝑥2
+ 𝑏𝑥 + 𝑐
• ex2 = sin(x)
• ex3 = sym (‘A𝑥3
+ 𝐵𝑥2
+ 𝐶𝑥 + 𝐹′)
• eq1= sym(‘ (x+1)^2=0 ’)
• eq2 = sym (‘ 𝐴𝑥2
= 1 ‘)
c and m are
not defined in
the workspace
30. Manipulating Symbolic
Expressions
■ MATLAB has a number of
functions designed to manipulate
symbolic variables.
• example:
■ poly2sym This function
requires a vector as input and
creates a symbolic variable.
■ sym2poly() This function
converts the symbolic variable to
a polynomial vector.
31. ■ expands(s) Multiplies out all the portions of the
expression or equation.
■ factor(s) Factors the expression or the equation.
■ collect(s) Collects the terms.
■ simplify(s) simplifies the equation or the expressions.
■ simple(s) simplifies to the shortest representation of
the expression
■ numden(s) Finds the numerator of an expression. This
function is not valid for equations.
■ [num,den] = numden(s) Finds both the numerator and
the denominator of an expression.
32. Practice:
■ Create a variable y1= 𝑥2
− 1 * (𝑥 + 1)2
■ Create a variable y2= 𝑥2
− 1/(𝑥 + 1)2
■ Use the numden function to extract the numerator and
denominator from y1 and y2.
■ Use the factor, expand ,collect and simplify functions on y1
and y2.
33. Solving Expressions & Equations
■ Solve() It can be used to determine the root of
expressions ,find numerical answers for a single variable,
to solve for an known symbolically.
■ MATLAB by default solves for x. If there is no x in the
expression , it finds the variable closest to x.
• To specify a variable to solve for:
The function
sets the
expression to
zero and solves
for roots
Solve for a
34. ■ solve(S) Solves an expression with a single variable
■ solve(S) Solves an equation with more than one variable
■ solve (S, y) Solves an equation with more than one variable for a
specific variable.
■ [A,B,C] = solve(S1, S2, S3) Solves a system of equations and
assigns the solutions to the variables names.
35. Solving System of Equations
■ To solve a system of equations ,
define the equations as symbolic
variables , then use the ‘solve’
command
■ To solve For example:
■ You can also use this , but keep in
mind that the order of variable is
important
■ Remember that :
x,y,z are still symbolic variables.
■ To change the symbolic
variable to a numeric variable:
Use ‘double’
36. Practice:
■ Solve the following system of equations, use
all the techniques you learned so far:
5x+6y-3z=10
3x-3y+2z = 14
2x-4y-12= 24
37. Substitution
■ We can substitute inside the
function with either numbers or
variables.
■ We can define a vector of numbers through
substitution.
■ Note:
• If variables have been previously explicitly
defined symbolically , the quote is not
required.
You substitute y in the place of x
You substitute x with 3
Substituting by listing an array
to the variables in the equation
39. Differentiation:
■ Use the command ‘diff(f)’
■ Consider the following:
■ diff(f ,’t’) Returns the
derivative of the expression f with
respect to the variable t
■ diff(f , n) Returns the nth
derivative.
■ diff(f, ‘t’, n) Returns the nth
derivative of the expression f with
respect to t.
Remember that the result is a
symbolic variable
40. Practice:
■ Find the first derivative:
• 𝑥2
+𝑥 + 1
• sin(x)
• ln(x)
■ Find the first partial derivative with respect to x:
• 𝑎𝑥2
+ 𝑏𝑥 + 𝑐
• tan 𝑥 + 𝑦
• 3𝑥 + 4𝑦 − 3𝑥𝑦
■ Find the second derivative with respect to y :
• 𝑦2
− 1
• 2𝑦 + 3𝑥2
41. Integration
■ To find the antiderivative,
use the command ‘int(f)’
■ int(f , ‘t’ )Returns the integral of f with
respect to variable t.
■ int(f , a ,b) Returns the integral of f
between the numeric values a , b.
■ int (f , ‘t’ , a ,b ) Returns the integral of f
with the respect to t between the numeric
values a, b .
• Note:
a , b can be either numbers or symbols
42. Practice:
■ Find the integral:
• 𝑥2
+𝑥 + 1
• sin(x)
• ln(x)
■ Integrate with respect to x:
• 𝑎𝑥2
+ 𝑏𝑥 + 𝑐
• tan 𝑥 + 𝑦
• 3𝑥 + 4𝑦 − 3𝑥𝑦
■ Integrate with respect to y :
• 𝑦2
− 1
• 2𝑦 + 3𝑥2
Try the same problems
with the limits
0
5
𝑓
43. Differential Equations
𝑦 = 𝑒𝑡
𝑑𝑦
𝑑𝑡
= 𝑒𝑡
■ dsolve() requires the user to enter
the differential equation ,using the
symbol D to specify derivatives
with respect to the independent
variable.
• Hint:
Do not use the letter D in your variable
names in DE. The function will
interpret D as a derivative.
The default
independent
variable in
MATLAB is
t
With
initial
condition
Specifying the
independent
variable
44. Differential Equations
■ We can also use the ‘dsolve’
function to solve systems of
differential equations:
dsolve(‘ eq1 , eq2 , … cond 1 ,
cond 2,…’)
Symbolic
elements
in an array
To access the
component
of the array
Or