SlideShare a Scribd company logo
1 of 44
Download to read offline
MATLAB TUTORIAL 4
By Norhan Abdalla
Outline:
■ Creating M-files
■ User Defined Functions
■ Solving Linear Equations
■ Symbolic Algebra
■ Calculus
CREATING M-FILES
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.
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’)
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.
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
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
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
USER DEFINED
FUNCTIONS
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
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 .
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
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
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
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
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
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.
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:
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.
SOLVING LINEAR
EQUATIONS
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]
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])
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:
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
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
SYMBOLIC ALGEBRA
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
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
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.
■ 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.
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.
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
■ 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.
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’
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
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
CALCULUS
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
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
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
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
𝑓
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
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

More Related Content

What's hot

Matlab-Data types and operators
Matlab-Data types and operatorsMatlab-Data types and operators
Matlab-Data types and operatorsLuckshay Batra
 
Basic matlab and matrix
Basic matlab and matrixBasic matlab and matrix
Basic matlab and matrixSaidur Rahman
 
Basics of programming in matlab
Basics of programming in matlabBasics of programming in matlab
Basics of programming in matlabAKANKSHA GUPTA
 
MATLAB BASICS
MATLAB BASICSMATLAB BASICS
MATLAB BASICSbutest
 
Matlab programming project
Matlab programming projectMatlab programming project
Matlab programming projectAssignmentpedia
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to MatlabAmr Rashed
 
Basic operators in matlab
Basic operators in matlabBasic operators in matlab
Basic operators in matlabrishiteta
 
Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)Retheesh Raj
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introductionAmeen San
 
Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4Randa Elanwar
 
Matlab from Beginner to Expert
Matlab from Beginner to ExpertMatlab from Beginner to Expert
Matlab from Beginner to Expertsmart-ideas
 
MATLAB Basics-Part1
MATLAB Basics-Part1MATLAB Basics-Part1
MATLAB Basics-Part1Elaf A.Saeed
 
Introduction to MATLAB 1
Introduction to MATLAB 1Introduction to MATLAB 1
Introduction to MATLAB 1Mohamed Gafar
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabBilawalBaloch1
 
Chapter 3.3
Chapter 3.3Chapter 3.3
Chapter 3.3sotlsoc
 

What's hot (20)

Matlab-Data types and operators
Matlab-Data types and operatorsMatlab-Data types and operators
Matlab-Data types and operators
 
Basic matlab and matrix
Basic matlab and matrixBasic matlab and matrix
Basic matlab and matrix
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Matlab Tutorial
Matlab TutorialMatlab Tutorial
Matlab Tutorial
 
Basics of programming in matlab
Basics of programming in matlabBasics of programming in matlab
Basics of programming in matlab
 
MATLAB BASICS
MATLAB BASICSMATLAB BASICS
MATLAB BASICS
 
Matlab programming project
Matlab programming projectMatlab programming project
Matlab programming project
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlab
 
Basic operators in matlab
Basic operators in matlabBasic operators in matlab
Basic operators in matlab
 
Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)
 
Matlab basic and image
Matlab basic and imageMatlab basic and image
Matlab basic and image
 
Palm m3 chapter1b
Palm m3 chapter1bPalm m3 chapter1b
Palm m3 chapter1b
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4
 
Matlab from Beginner to Expert
Matlab from Beginner to ExpertMatlab from Beginner to Expert
Matlab from Beginner to Expert
 
C,C++ In Matlab
C,C++ In MatlabC,C++ In Matlab
C,C++ In Matlab
 
MATLAB Basics-Part1
MATLAB Basics-Part1MATLAB Basics-Part1
MATLAB Basics-Part1
 
Introduction to MATLAB 1
Introduction to MATLAB 1Introduction to MATLAB 1
Introduction to MATLAB 1
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Chapter 3.3
Chapter 3.3Chapter 3.3
Chapter 3.3
 

Similar to Matlab tutorial 4

Handout2.pdf
Handout2.pdfHandout2.pdf
Handout2.pdfShoukat13
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsA complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsMukesh Kumar
 
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkMATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkreddyprasad reddyvari
 
Dsp manual completed2
Dsp manual completed2Dsp manual completed2
Dsp manual completed2bilawalali74
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersMurshida ck
 
Section-6-User-Defined-Functions.pdf
Section-6-User-Defined-Functions.pdfSection-6-User-Defined-Functions.pdf
Section-6-User-Defined-Functions.pdfjohnkyllelumacang699
 
Matlab ch1 intro
Matlab ch1 introMatlab ch1 intro
Matlab ch1 introRagu Nathan
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondMahuaPal6
 
Lecture 01 variables scripts and operations
Lecture 01   variables scripts and operationsLecture 01   variables scripts and operations
Lecture 01 variables scripts and operationsSmee Kaem Chann
 

Similar to Matlab tutorial 4 (20)

introduction to matlab.pptx
introduction to matlab.pptxintroduction to matlab.pptx
introduction to matlab.pptx
 
MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
 
Matlab tutorial 3
Matlab tutorial 3Matlab tutorial 3
Matlab tutorial 3
 
Handout2.pdf
Handout2.pdfHandout2.pdf
Handout2.pdf
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsA complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
 
Matlab Tutorial.ppt
Matlab Tutorial.pptMatlab Tutorial.ppt
Matlab Tutorial.ppt
 
Image processing
Image processingImage processing
Image processing
 
Introduction to Matlab.ppt
Introduction to Matlab.pptIntroduction to Matlab.ppt
Introduction to Matlab.ppt
 
Scala qq
Scala qqScala qq
Scala qq
 
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkMATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
 
Dsp manual completed2
Dsp manual completed2Dsp manual completed2
Dsp manual completed2
 
presentation.pptx
presentation.pptxpresentation.pptx
presentation.pptx
 
1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
Section-6-User-Defined-Functions.pdf
Section-6-User-Defined-Functions.pdfSection-6-User-Defined-Functions.pdf
Section-6-User-Defined-Functions.pdf
 
Matlab ch1 intro
Matlab ch1 introMatlab ch1 intro
Matlab ch1 intro
 
Matlab booklet
Matlab bookletMatlab booklet
Matlab booklet
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
 
Lecture 01 variables scripts and operations
Lecture 01   variables scripts and operationsLecture 01   variables scripts and operations
Lecture 01 variables scripts and operations
 

Recently uploaded

What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 

Recently uploaded (20)

Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 

Matlab tutorial 4

  • 1. MATLAB TUTORIAL 4 By Norhan Abdalla
  • 2. Outline: ■ Creating M-files ■ User Defined Functions ■ Solving Linear Equations ■ Symbolic Algebra ■ 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