SlideShare a Scribd company logo
ENG105
Engineering and Computing Skills
Author
image here
Outline
Chapter 1: Introduction to Matlab
Chapter 2: Algorithmic Structures in MATLAB
Chapter 3: Mathematical Applications in
MATLAB
Chapter 4: Polar Coordinates in MATLAB &
Integration Using Polar Coordinates
Chapter 5: Definite and Indefinite Integrals
Chapter 6: Symbolic Math in MATLAB
Chapter 1: Introduction to Matlab
Author
image here
Outline
Introduction
Matlab for Windows
Variables
Matlab as a Calculator
Constants and Math Functions
Display Function & Formats
Plots
Programming in Matlab
Scripts
Functions
5
A program for doing numerical computation. Originally
designed for solving linear algebra type problems using
matrices.
Matlab
6
Display Windows
7
Desktop menus
File menu
New
Create new Matlab program file (m-file)
Open existing m-file
Import data
Set path
Open recent m-files
Matlab GUI
8
Edit Menu
Copy, cut, paste
Find and replace
phrases
Clear command history,
workspace
Desktop Menu
Change appearance of
desktop
Select windows to
display
MATLAB GUI
9
Getting Help
type one of following commands in the command window:
help  lists all the help topic
help command  provides help for the specified command
Example:
>> help sqrt
SQRT Square root.
SQRT(X) is the square root of the elements of X. Complex
results are produced if X is not positive.
help help  provides information on the help command use
10
Variables
Variables are named memory locations that can be assigned a value by
the user or programmer.
The system can retrieve , or “remember” the value of a variable.
Variable names:
Must start with a letter
May contain only letters, digits, and the underscore “_”
Matlab is case sensitive, i.e. one & OnE are different variables.
Assignment statement:
Variable = number;
Variable = expression;
NOTE: when a semi-colon ”;” is placed at the
end of each command, the result is not
displayed.
11
Variable Examples
>> tutorial = 1234;
>> tutorial = 1234
tutorial = ?
>> a  ??? Undefined function or variable 'a'.
>> a=2 a = ?
>> a+3 ans = ?
>> sqrt(a+14) ans = ?
>> a=a+12 a = ?
12
String Variables
>> a = 'This is a string'
a = ?
>> b= 'Another string'
b = ?
>> a + b
 ??? Error using ==> plus Matrix dimensions must agree.
13
Special Variables
ans : default variable name for the result
pi: π = 3.1415926…………
eps: ԑ = 2.2204e-016, smallest amount by which 2 numbers can differ.
Inf or inf : ∞, infinity
NaN or nan: not-a-number
14
Defining Symbolic Variables & Viewing Variables
Use sym to create a symbolic variable x:
Use syms to create several symbolic variables at one time
Use who to view all variables in the workspace
» x=sym('x');
» syms y a b
» who
Your variables are:
Use whos to view all workspace variables with their associated size,
bytes, and class information
» n=1.0;t=[1.1 2.2 3.3];
» whos
15
Symbolic Expressions
Symbolic expressions are expressions that contain symbolic variables
Example:
» f = 2*x^2 + x + 1;
» g = a*x^2 + b*x + 5
g =?
16
MATLAB as a Calculator
MATLAB can be used as an expression evaluator.
For example, to “evaluate” pi type
>> pi
ans = ?
x=pi % the value of pi is assigned to variable x
Try the following examples:
>> r = sqrt(9)
r = ?
>> m = sin(pi/2)
m = ?
17
Arithmetic Operators in MATLAB
The contents of all bracketed expressions are evaluated, starting from the
innermost brackets and working out.
All exponentials are evaluated, working from left to right.
All multiplications and divisions are evaluated, working from left to right.
All additions and subtractions are evaluated, working from left to right.
Operators:
+ for addition
- For subtraction
* for multiplication
/ for division
^ for power
18
Operator Precedence
Precedence is the order in which operations are performed.
(Highest) Parenthesis . anything in parenthesis is done first
Exponentiation
Multiplication, division
(Lowest) Addition, subtraction
Spaces are ignored
Solve the following examples:
>> 2 + 3 * 4
>> 2 * 3 ^ 2
>> (2 + 3) * 4
>> (2^(2 + 3)) * 4
19
Constants and Functions
>> eps
ans = 2.2204e-016
>> sin(pi/2)
ans = 1
>> log(1000)
ans = 6.9078
>> log10(1000)
ans = 3
20
Elementary Math Functions
>> help elfun
Elementary math functions.
Trigonometric.
sin - Sine.
sinh - Hyperbolic sine.
asin - Inverse sine.
asinh - Inverse hyperbolic sine.
cos - Cosine.
cosh - Hyperbolic cosine.
acos - Inverse cosine.
acosh - Inverse hyperbolic cosine.
tan - Tangent.
tanh - Hyperbolic tangent.
21
Elementary Math Functions
exp Exponential (e^x).
log Natural logarithm.
log10 Common (base 10) logarithm.
log2 Base 2 logarithm and dissect floating point number.
sqrt Square root.
Exponential function examples:
>> exp(log(3))
>> log(exp(3))
>> log2(32)
>> log2(pow2(5))
22
Elementary Math Functions
Rounding and remainder
fix Round towards zero.
floor Round towards minus infinity.
ceil Round towards plus infinity.
round Round towards nearest integer.
mod Modulus (signed remainder after division).
rem Remainder after division.
sign Signum.
23
Rounding Examples
+
round(2.7) = ?
round(2.3) = ?
fix(2.3) = ?
fix(2.7) =?
ceil(2.3) = ?
ceil(2.7) = ?
floor(2.3) = ?
floor(2.7) = ?
-
round(-2.7) = ?
round(-2.3) = ?
fix(-2.3) = ?
fix(-2.7) = ?
ceil(-2.3) = ?
ceil(-2.7) = ?
floor(-2.3) = ?
floor(-2.7) = ?
24
Mathematical Functions in MATLAB
Some of the Matlab built-in functions are:
abs(x) for absolute value
sqrt (x) for square root
sin(x) for sine
cos(x) for cosine
tan(x) for tangent
cot(x) for cotangent
log(x) for natural logarithm
exp(x) for exponentioal
atan(x) for inverse tangent or arctan
sinh(x) for sine hyperbolic
25
disp Function
Used to display numbers and strings.
The values displayed at the screen don’t necessarily include all the
information.
It is possible to change the display format.
Examples
>> disp(3)  3
>> disp('abc')  abc
>> format long
>> pi  ans = ?
>> format short
>> pi  ans = ?
26
fprintf Function
Advanced version of the disp dunction
Displays text and variables simultaneously
C++ principles based
Syntax: fprintf(‘text %var1_place_type text’, var1_name)
Example:
a=65;
b=97;
fprintf('the sum of %i and %i is %i',a,b,a+b)
fprintf('the ASCII code of %s is %i',a,a)
27
fprintf arguments
Type of variables:
%i: integer
%d: double
%f: float
%c: char
%s: string
Possibility to control the number of decimal places
Ex: fprintf(‘a with three decimal places: %.3f',a)
Ex: fprintf('a with 4 numbers: %.4i',a)
All the text in the same line? Use n for a new line
28
Drawing in MATLAB
Possibility to draw figures and curves in MATLAB
The x axis limit need to be specified most of the time
 ex: x= -6 : 0.1 : 6
Different plot types:
Plot: draw the curve of an equation that depends on a variable
Ezplot: plot with a predefined range of [-2π, 2π]
Subplot: draw many plot in the same window
Figure: create a separate window for a new plot
Ex: syms x
ezplot(sin(x))
figure
ezplot(cos(x))
29
plot Command Syntax
Plot(x,y,’r’): plot x in function of y with the ‘r’ (red style)
‘r’: red ‘b’:blue ‘black’: black
‘x’: cross ‘o’: circle ‘.’: Points
plot(x,y1,'--',x,y2,'-',x,y3,':')  plot multiple plots
xlabel(‘name'):  give a name to X-axis
ylabel(‘name'):  give a name to Y-axis
legend(‘y1',‘y2',‘y2')  display each plot’s legend
title(‘name')  display the plot title
axis([0 2*pi -3 3]):  define the X & Y axis limits
hold on  multiple displays in 1 plot
30
In Matlab, we can plot a symbolic function over one variable by using the
ezplot function.
Plotting Symbolic Function
>> syms a b c x % define symbolic math variables
>> y = sin(x)
>> ezplot(y)
>> f = sin(x);
>> ezsurf(f) % another type of plotting example
>> g = cos(y);
>> ezsurf(f+g);
31
Draw multiple independent plots in the same window
Syntax: subplot(x,y,id)
subplot Command
syms x
subplot(2,2,1)
ezplot(cos(x))
subplot(2,2,2)
ezplot(sin(x))
subplot(2,2,3)
ezplot(tan(x))
subplot(2,2,4)
ezplot(atan(x))
Programming in MATLAB
33
Script and Functions: Script Files
A user-created file with a sequence of MATLAB commands in it.
A text file containing script or function or program to run
The file must be saved with a ‘.m’ extension to its name, thereby, making
it an M-file.
Executed by typing its name (without the ‘.m’ extension) at the command
prompt.
34
Create a .m File
From the File menu, select New M-File.
→
A new edit window should appear.
35
Example 1:
in Command window
>> example1
C = ?
Example 1
in m-file:
A= 2;
B=3;
C=A+B
Save as a file name example1.m
36
Find the force if the mass is 10 Kg and the acceleration is 100m/sec2.
Newton’s Law: F = m .γ (Force = mass x acceleration) (γ = 100)
Example 2
Create a new script (example2.m)
m = 10;
gamma = 100;
Force =m * gamma
To run the above file, type in the command window
>>example2
37
Script and Functions: Function Files
A m-file also , like a script file, except that the variables are all local.
A function file begins with a function definition line containing a well-
defined list of inputs and outputs.
Without that line, the file becomes a simple script file.
The syntax of the function definition line is:
function [ output variables ] = function_name ( input variables );
It is recommended for the function_name to be the same as the
filename (without the ‘.m’ extension) in which the function is written.
Example: if the name of the function is projectile it must be written and
saved in a file with the name projectile.m.
WARNING!
for the scipt or function name
file, avoid using the name of a
MATLAB command such as plot,
sqrt, abs…
39
Write a MATLAB function called sumy that adds two input numbers and
returns the result minus 2
Example 3
function out = sumy(x,y)
out=x+y-2
Save with filename sumy.m , then type in the command window:
>>sumy(6,5) % 6 and 5 are arbitrary values chosen by the user
out = ?
40
Solution
Function file:
function [area, volume] = cyl(h, r)
% function to compute the area and volume of a cylinder
base = pi * r^2;
volume = base * h
area = 2*pi*r * h + 2*base
Store the function in cyl.m, then, in
command window:
>> cyl(6, 4)
area = ?
vol = ?
Example 3: Measuring a Solid Object
We need to compute the volume and
surface area of this cylinder object:
Formulas: b: base, h: height
Base: b= π r²
Volume = b h
Area=2 π r h + 2 b
Exercises
42
Create a m-file and enter the following
statements in the m-file:
A = [1 2 3; 3 3 4; 2 3 3];
b = [1; 1; 2];
x = Ab
Save the file, (e.g. example1.m)
In the command line, type:
>> example1
x = ?
Example 1:
Consider the system of equations:
x + 2y + 3z = 1
3x + 3y + 4z = 1
2x + 3y + 3z = 2
Find the solution x to the system of
equations.
43
Create a file, say example2.m, which
contains the following commands:
x = 0:pi/100:2*pi;
y1 = 2*cos(x);
y2 = cos(x);
y3 = 0.5*cos(x);
plot(x,y1,'--',x,y2,'-',x,y3,':')
xlabel('Range')
ylabel('Cosine functions')
legend('2*cos(x)','cos(x)','0.5*cos(x)')
title('Example of multiple plots')
axis([0 2*pi -3 3])
Run the file by typing example2 in the
Command Window.
Example 2:
Plot the following cosine functions, y1
= 2 cos(x)
y2 = cos(x)
y3 = 0.5 * cos(x)
in the interval 0  x  2.
44
game1 = input('Enter the points
scored in the first game ');
game2 = input('Enter the points
scored in the second game ');
game3 = input('Enter the points
scored in the third game ');
average = (game1+game2+game3)/3
The following shows the command
prompt when this script file (saved as
example3) is executed.
>> example3
>> Enter the points scored in the
first game xx
>> Enter the points scored in the
second game yy
>> Enter the points scored in the
third game zz
average = ?
Example 3:
Create a script file that calculates the
average of points scored in three
games.
The point from each game are
assigned to a variable by using the
’input’ command.
45
Create a script in a file computes area of triangle
Example 4
b=5;
h=3;
area=0.5*(b*h)
area = ?
46
Scripts VS Functions
To calculate the area of another triangle using the same script, it is
possible to update the values of b and h in the script and re-run it. the
script stores the result each time in a variable named a that is in the
base workspace.
Instead of manually updating the script each time, it is possible to make
a more flexible program by converting the script to a function.
Replace the statements that assign values to b and h with a function
declaration statement.
The declaration includes
the function keyword
the names of input and output arguments
the name of the function.
47
Redo example 4 using the function method
Example 5
function a = triarea(b,h)
a = 0.5*(b.* h);
After saving the file, call the function with different values
a1 = triarea(1,5)
a1 = ?
a2 = triarea(2,10)
a2= ?
a3 = triarea(3,6)
a3= ?
Functions have their own workspace
(local), separate from the base
workspace (global). So, none of the
calls to the function triarea overwrite
the value of a in the base workspace.
Instead, the function assigns the
results to variables a1, a2, and a3.
49
HOMEWORK 1
Page no: 28 problem no:9&11
Page no: 30 problem no:21
Page no: 31 problem no:27
Page no: 164 problem no:6
Submit- next week class
Chapter 2: Algorithmic Structures in MATLAB
Slim Chtourou
Lecturer
slim.chtourou@ieee.org
www.slim.fr.mu
Outline
For: iterative statement
Iterative applications
Taylor series
If: conditional statement
Conditional applications
52
The for loop
The general form of for loop is:
for i=beginning :step: final
program statements
end
Where beginning, step, and final are integers or real numbers.
Example 1:
Find the sum of the integers from 5 to 100.
53
Solution
Open an m file (example1.m)
sum=0;
for i=5:100
sum=sum+i;
end
disp(‘sum’)
disp(sum)
To run the above file, type in the command window
>>example1
54
Find the sum of the odd integers between 1 and 100.
Example 2
sum=0;
for i=1:2:100
sum=sum+i;
end
disp(‘sum of odd integers between 1 and 100 is:’);
disp(sum)
55
Find the sum of the first 10 terms as below.
Example 3
sum=0;
for i=1:10
sum=sum+1/i;
end
disp(‘sum of the 10 terms is:’);
disp(sum)
10
1
9
1
8
1
7
1
6
1
5
1
4
1
3
1
2
1
1 








56
Functions (reminder)
The general form of a function in MATLAB is
function [rv1 rv2 … rvn]=Function_Name(pv1,pv2,..,pvn)
where
rv1, rv2,.. are the outputs
pv1, pv2,.. are the inputs.
The body of the function will contain the relations between the
outputs and inputs.
57
Write a function “sumN” that finds the sum of the first N term of the series
below.
Example 4
function s=sumN(N)
s=0;
for i=1:N
s=s+1/i;
end
To run this function code, type in the command window:
>>sumN(5);
N
1
....
8
1
7
1
6
1
5
1
4
1
3
1
2
1
1 








58
Write a function “expN” that finds the sum of the first N term of the series
below for a given value of x.
Example 5
function s=expN(N,x)
s=0;
for i=0:N
s=s+x^i/factorial(i);
end
In the command window:
>>p=expN(5,1);


N
i
i
i
x
0 !
Conditional Statements
60
if statement
Conditional statement are used to perform certain task if certain
conditions are met or not
The general structure of if statement is:
if expression
statements
elseif expression
statements
else
statements
end
61
n1=input('enter number1 ');
n2=input('enter number2 ');
if n1>n2
disp(n1)
else
disp(n2)
end
Example 1
Create a program that accepts two
numbers and display the bigger one
62
n1=input('enter number1 ');
n2=input('enter number2 ');
if n1>n2
disp('n1>n2')
elseif n1<n2
disp('n1<n2')
else
disp('the numbers are identical')
end
Example 2
Create a program that compares two
numbers inputted by the user and
display the comparison result
63
nrows = 6;
ncols = 6;
A = ones(nrows,ncols)
for c = 1:ncols
for r = 1:nrows
if r == c
A(r,c) = 2;
elseif abs(r-c) == 1
A(r,c) = -1;
else
A(r,c) = 0;
end
end
end
A
Example 3
1-Create a matrix and fill it with 1
2-Loop through the matrix and assign
each element a new value:
2 on the main diagonal
-1 on the adjacent diagonals
0 everywhere else.
64
syms hw pr mt et total
nbr=input('enter the number of student ')
for i=1:nbr
fprintf('student %in',i)
hw(i)=input('enter the homework grade ');
pr(i)=input('enter the project grade ');
mt(i)=input('enter the midterm exam grade ');
et(i)=input('enter the endterm exam grade ');
end
for i=1:nbr
moy(i)=hw(i)+pr(i)+mt(i)+ et(i);
end
for i=1:nbr
if moy(i)<60
fprintf('student %i got %d,
so he has failedn',i,moy(i))
else
fprintf('student %i got %d, so he
has passedn',i,moy(i))
end
end
Example 4
Create a program that collects the n
students’ grades (Homework, Project,
mid-term & End-term) and
determines if the student has passed
or failed the course
Homework 2
Redo the previous example
while taking all possible grades
(F, D, D+, C, C+, B, B+, A & a+)
into account
Chapter 3: Mathematical Applications in
MATLAB
Slim Chtourou
Lecturer
slim.chtourou@ieee.org
www.slim.fr.mu
Outline
Integration
Derivation
Taylor series
68
Matlab can also compute many integrals and derivatives that you might find
in Calculus or many advanced engineering courses.
The key functions are int for integration and diff for derivation.
Derivation and Integration
>> syms x;
>> f = sin(5*x)
>>diff(f)
ans = ?
69
Derivation and Integration (2nd and Higher Derivative)
>> f = x^3
>> diff(f) % 1st derivative
ans = ?
>> diff(f,2) % 2nd derivative
ans = ?
>> diff(f,3) % 3rd derivative
ans = ?
>> diff(f,4) % 4th derivative
ans = ?
70
Partial Differential Equations
Sometimes, an expression can have multiple variables.
To compute the derivative of the function with respect to one variable,
use a second parameter to the diff function:
>> syms x t;
>> f = sin( x * t )
>> diff(f,t) % derivative of f with respect to t
ans = ?
71
By using the int function, in the same way we use the diff function, we can
ask Matlab to do symbolic integration for us.
Integration
>> syms x t;
>> f = x * x ;
>>int(f)
ans = ?
72
As you (should) know, a definite integral represents the area under a curve from
a given start point to a given end point.
Try to find how much area is under the curve f(x) = x^3; for [0..10], [-10..10], [-
10..0]
Definite Integrals
>> syms x;
f= x^3
>> int(x^3,0,10)
ans = ?
>> int(x^3,-10,10)
ans = ?
>> int(x^3,-10,0)
ans = ?
MATLAB can find the derivative of symbolic
expressions. Higher derivatives can also be
found easily. These derivatives can be
evaluated for arbitrary values of the
independent variable.
74
Enter:
syms x
g = x^2*cos(x)
Now enter:
diff(g, x)
Then enter:
diff(g, x, 2)
How would you calculate the third derivative?
Example:1
First we declare x to be a symbolic
variable and define g to be the
function given by g(x) = x2
cos(x).
75
Example 2
To calculate the derivative of an expression that you have not yet
entered, just replace g by the expression. For example, enter:
diff(x^3-x^2+2, x)
Now insert a symbolic constant a into the expression. Enter:
syms a
diff(x^3 - a*x^2 + 2, x)
Then change the final x to an a. That is, enter:
diff(x^3 - a*x^2 + 2, a)
What is the role of the symbol after the comma in the differentiation
expression?
76
Example 3
Evaluate the derivative dg/dx at x = 2.1.
Enter:
gp=diff(g, x)
Then enter:
subs(gp, x, 2.1)
Alternatively, you could enter:
subs( diff(g, x), x , 2.1 )
Check your understanding so far by using
MATLAB to calculate the second derivative of
tan(x6
- 3x + 5) at x = 3/2.
78
Calculate the derivative of the function F(x)=x3
- cos(x)
Example 4
>> syms x
>> f=x^3-cos(x);
>> g=diff(f)
g = ?
79
Obtain the derivative of the following function according to y:
F(x,y)=x² +(y+5)3
Example 5
Matlab command entries:
>> syms x y
>> f=x^2+(y+5)^3;
>> diff(f,y)
ans = ?
Note that in this case, the command diff(f,y) is equivalent to
80
Find the derivative of f(x)=sin(ex
).
Example 6
>> syms x
>> f=sin(exp(x));
>> diff(f)
ans = ?
81
To compute the partial derivative of an expression with respect to some
variable we specify that variable as an additional argument ‘diff’
f(x,y)=x3
y4
+ysin(x)
Example 7
>> syms x y
>> f=x^3*y^4+y*sin(x)
>> diff(f,x)
ans = ?
>> diff(f,y)
ans = ?
82
Taylor Series
The Taylor series is a representation of a given function as an infinite
sum of terms calculated from its derivatives values at a single point.
If the series is centered at zero, the Taylor series is Maclaurin series.
It is a common practice to use a finite number of terms to approximate
the function.
Taylor series of order 5 is an approximation of f(x) as a polynomial of
degree 5.
The general expression of Taylor series for an analytic function f(x) about
the base point x=a is:
fm
(a) is the mth
derivative of f(x) at the point a.





0 !
)
(
)
(
)
(
m
m
m
m
a
a
x
x
f
f
83
Use the "taylor" function to create a taylor series
Taylor Command
>> syms x
>> f = taylor(log(1+x))
f = ?
84
Taylor Series
Two methods for MATLAB to find the Taylor series expansion of f(x) at x=a
Method 1: Using the general Taylor series summation and programming
it using function and for loops as explained in the example 5.
Method 2: Using the MATLAB function : taylor, In general:
taylor(f,n,a) returns the Taylor series expansion of f(x) of order n-1 at
the base point x=a.
taylor(f,n) returns the Taylor series expansion of f(x) of order n-1 at
the base point x=0.
taylor(f,a) returns the Taylor series expansion of f(x) of order 5 at the
base point x=a.
Note: f must be a symbolic expression representing f(x)
85
Example 8
Given a function f(x)=sin(x). Write a program that finds the Taylor series
expansion of f(x) at x=0 of degree 3.
Plot f(x) and its Taylor series approximation of degree 3 on the same
graph for x in the range [-pi,pi]
Add Taylor series of degrees 5, 7 to the same plot.
Which Taylor series better approximates f(x).
What is your conclusion?
86
Solution (1/2)
Open a script file example6.m
syms x;
f=sin(x);
t3=taylor(f,4); %Taylor series at x=0 of degree 3
xd=-pi:pi/20:pi;
yd=subs(f,x,xd); %This evaluates f(x) at xd (symbolic).
td3=subs(t3,x,xd); %This evaluates t(x) at xd.
plot(xd,yd,’y’);
hold on;
plot(xd,td3,’m’);
87
t5=taylor(f,6); %5th deg Taylor series at x=0
t7=taylor(f,8); %7th deg Taylor series at x=0
td5=subs(t5,x,xd);
td7=subs(t7,x,xd);
plot(xd,td5,’r’);
hold on;
plot(xd,td7,’b’);
Legend(‘exact’,’Taylor 3’,’Taylor 5’,’Taylor
7’);
xlabel(‘x’);
ylabel(‘function’)
Solution (2/2)
88
syms x;
f=sin(x);
t3=taylor(f,4); %3rd deg Taylor series at x=0
f_inline=inline(char(f)); %f:symbolic  function
t3_inline=inline(char(t3));
fplot(f_inline,[-pi ,pi],'b');
hold on;
fplot(t3_inline,[-pi, pi],'r');
Legend('exact','Taylor 3');
xlabel('x');
ylabel('function')
Example 8(Another Method)
89
Find the following integration using Taylor series of order 6:
Example 9
syms x;
f=exp(x^2);
t6=taylor(f,7); %Taylor series at x=0 of degree 6
int(t6,-1,1) %Integration of t6
Ans= ?
dx
ex


1
1
2
90
Example 9 Solution (2nd
Method) (1/3)
The series expansion of ex is known:
The series expansion of ex2
can then be found by replacing x with x²
The integration of ex
2
can then be found




0 !
i
i
x
i
x
e








0
2
0
2
!
!
)
(
2
i
i
i
i
x
i
x
i
x
e
)
(
)
!
)(
1
2
(
!
! 0
1
2
0
2
0
2
2
x
f
i
i
x
dx
i
x
dx
i
x
dx
e
i
i
i
i
i
i
x




 











)
1
(
)
1
(
1
1
2





f
f
dx
ex
91
So, this method depends on writing the MATLAB function f(x) and finding f(1) -
f(-1)
Example 9 Solution (2nd
Method) (2/3)
function s=f(x)
s=0;
for i=0:100
s=s+ x^(2*i+1)/((2*i+1)*factorial(i));
end
In the command window, type:
>> int_result=f(1)-f(-1)
int_result=?
92
In the previous example, plot f(x) and its Taylor
approximation t6(x) on the same graph for -1 ≤ x ≤ 1
syms x;
f=exp(x^2);
xd=-1:0.1:1;
yd=subs(f,xd);
plot(xd,yd,’r’);
hold on;
t6=taylor(f,7); %Taylor of degree 6
td=subs(t6,xd);
plot(xd,td,’b’);
xlabel(‘x’);
ylabel(‘functions’);
legend(‘f(x)’,’Taylor’)
Example 9 Solution (2nd
Method) (3/3)
93
Find the taylor series expansion of order 3 about the point x=1 of the function
Example 10
syms x;
f = 1/(1+x);
t3 = taylor(f,4,1)
T3 = ?
x
x
f


1
1
)
(
94
Find the taylor series expansion of order 3 about the point x=0 of the function
Example 11
syms x;
f=1/(1+x);
t3=taylor(f,4)
t3 = ?
x
x
f


1
1
)
(
Chapter 4: Polar Coordinates in MATLAB &
Integration Using Polar Coordinates
Slim Chtourou
Lecturer
slim.chtourou@ieee.org
www.slim.fr.mu
Outline
Converting Polar Coordinates to Rectangular
Converting Rectangular Coordinates to Polar
Plotting Polar Coordinates
97
Every point can be expressed in:
Rectangulat coordinates: (x,y)
Polar coordinates: (r,θ)
Polar and Rectangular Coordinates
98
[x,y] = pol2cart(theta,r)
[theta,r] = cart2pol(x,y)
angle comes first
Converting Between Polar And Cartesian in Matlab
>>[x,y] = pol2cart(pi/4,1)
x = ?
y = ?
>>[theta,r] = cart2pol(0,-4)
theta = ?
r = ?
99
Calculate the cartesian
coordinates of the two
red points •
Exercise
θ is expressed in radians
100
Polar Command in Matlab
The Matlab command:
 >> polar (theta,r,s);
Plots the points defined in polar coordinates as (r,theta) for all values of r
and theta
s is a string that defines the style of the plot
Ex: ‘y’: yellow | ‘r’: red
Reminder: theta must be in radians
101
Use MATLAB to plot the following points in polar coordinates:
r=5, θ=0° | r=5, θ=60° | r=3, θ=180° | r=3, θ=300° | r=3, θ=-30°
Example 1
Solution:
Create a script file: example1.m
>> r=[5 5 3 3 3];
>> theta=[0 60 180 300 -30]*pi/180; %Convert to radians
>> polar(theta , r, 'x');
102
103
Conversion Between Polar and Rectangular
Polar to Rectangular
X = r cosθ
Y = r sinθ
Rectangular to Polar
r =
θ = tan-1
()
104
Solution:
>>x=3;
>>y=4;
>>r=sqrt(x^2+y^2);
>>theta=atan2(y,x); % in radians
>>theta = theta *180/pi % in degrees
Answer:
r=?
theta=?
Example 2
Find the polar coordinates of a point
(x,y) of your choice using Matlab as a
calculator
105
Solution:
>>r=5;
>>theta=53*pi/180; %convert to radians
>>x = r * cos(theta);
>>x = r * sin(theta);
Answer:
x=3
y=4
Example 3
Find the rectangular coordinates of
the point (5,53°) using Matlab as a
calculator
106
Solution:
Open a script file example1d.m
>>r=[5 5 3 3 3];
>>theta=[0 60 180 300 -30]*pi/180;%to rad
>>polar(theta,r,’x’);
>>hold on;
>>x=r .* cos(theta); % from polar to rectangular
>>y=r .* sin(theta); % from polar to rectangular
>>plot(x,y, ‘o’);
Example 3
Repeat Example 1 and plot the given
points using the polar to rectangular
conversion relation. Add the two
examples on one plot.
107
108
Using Matlab, draw the curve r = sin(θ)
Example 5
Solution:
Open a script file example5.m
theta=linspace(0,2*pi,200); %generates 200 points between 0 and 2π
r=sin(theta);
polar(theta,r,’r’);
109
110
Using Matlab, draw the curve r = cos(2θ)
Example 6
Solution:
Open a script file example6.m
>>theta=linspace(0,2*pi,200); %generates 200 points between 0 and 2π
>>r=cos(2*theta);
>>polar(theta,r,’r’);
111
112
Area in Polar Coordinates (from calculus II)
The area bounded by the curves r1(θ) , r2(θ), θ = θ1 and θ = θ2 is given by:
θ1 and θ2 must be in radians
Example 7:
Find the area bounded by the curves r = 2 sinθ, θ1 = 45°, θ2 = 135° and the
origin
Show all curves in one plot



d
r
r )
(
2
1 2
1
2
2
2
1

 
Area
113
1-plot the 3 curves
Open script file example7.m
>>theta=linspace(0,2*pi); %or theta=0:2*pi/100:2*pi;
>>r=2*sin(theta);
>>polar(theta,r,’r’); %plots r=2 sin(theta)
>>hold on;
>>r=linspace(0,2);
>>theta=(45*pi/180)*ones(size(r));
>>polar(theta,r,’b’);
>>hold on;
>>r=linspace(0,2);
>>theta=(135*pi/180)*ones(size(r));
>>polar(theta,r,’g’);
Solution (1/2)
114
Solution (2/2)
2-form the integration and put the limits:
3-Go to command window of MATLAB and do the integration using int:
>>syms theta;
>>area=eval(0.5 * int(4 * sin(theta)^2 , pi/4 , 3*pi/4))
Answer:
area=?






d
)
0
sin
4
(
2
1 4
3
4
2

 


Area



d
r
r )
(
2
1 2
1
2
2
2
1

 
Area
115
Determine the area of the region that lies inside
r= 3 +2 sinθ and r=2, show the region
Solution
1-plot the two curves:
Open example8.m
>>theta=linspace(0,2*pi)
>>r=2*ones(size(theta));
>>polar(theta,r,’r’);
>>hold on;
>>r=3+2*sin(theta);
>>polar(theta,r);
Example 8
116
Solution (2/2)
2-form the integration and put the limits:
3-Go to command window of MATLAB and do the integration using int:
>>syms theta;
>>area=eval(0.5*int((3+2*sin(theta))^2-4,-pi/6,7*pi/6))
Answer:
area=?






d
Area ]
4
)
sin
2
3
[(
2
1 6
7
6
2


 






d
Area r
r )
(
2
1 2
1
2
2
2
1

 
Chapter 5: Definite and Indefinite Integrals
Slim Chtourou
Lecturer
slim.chtourou@ieee.org
www.slim.fr.mu
Outline
Definite and Indefinite Integrals
Integral Pairs
Closed Form Integrals
Int Command
Closed Form Example
Multiple Independent Variable Example
Numerical Integration
quad Command
Numerical Integration Example
Closed Form and Numerical Integration Example
119
Definite & Indefinite Integrals
A definite integral represents the area under a curve f(x) between the
lower limit ‘a’ and the upper limit ‘b’
An integral is considered to be indefinite if the upper and lower limits
are not specified


b
a
DEFINITE dx
x
f
I )
(

 dx
x
f
IINDEFINITE )
(
120
Integral Pairs
Some indefinite integrals can be considered of as the inverse of
differentiation
Common examples:
Note: due to initial conditions, arbitrary integral pairs are not unique
and may differ by a constant of integration, c
c
ax
adx 


c
n
ax
dx
ax
n
n




 1
1
c
a
e
dx
e
ax
ax



c
b
bx
a
dx
bx
a 


)
sin(
)
cos(
c
b
bx
a
dx
bx
a 



)
cos(
)
sin(
c
x
a
dx
x
a


 )
ln(
121
Closed Form Integrals
Closed form integrals can be expressed as explicit functions.
The integral pairs on the previous slide are examples of closed form
integrals.
Techniques such as partial fraction expansion, integration by parts, and
integration by substitution can be used to express some integrals in
closed form.
It is not always possible to find the closed form for the integral of an
arbitrary function
122
Evaluation of Definite Integral
If a closed form indefinite integral exists, it can be used to evaluate a
definite integral over a region of integration
An integral from an arbitrary lower limit to a fixed upper limit is denoted
as:
Thus definite integral from a lower limit a to an upper limit b can be
evaluated using:


x
du
u
f
x
F )
(
)
(


 

b
x
x
a
b
a
dx
x
f
dx
x
f
dx
x
f
0
0
)
(
)
(
)
(
b
a
b
a
x
F
a
F
b
F
dx
x
f )
(
)
(
)
(
)
( 



123
int command
The int command is used to solve integrals which can be expressed in
closed form
int(s) returns the indefinite integral of the symbolic variable s with
respect to its default symbolic variable
int(s,v) returns the indefinite integral of the symbolic variable s with
respect to the symbolic variable v
int(s,a,b) returns the definite integral of the symbolic variable s with
respect its default symbolic variable from a to b
int(s,v,a,b) returns the definite integral of the symbolic variable s with
respect to the symbolic variable v from a to b
124
Closed form Example
Given the function, f(x):
1- Use the int command to determine the Closed Form
Indefinite Integral, F(x):
2- From the closed form integral, F(x), determine the definite
integral of f(x) from 0 to p/2
3- Use the int command to directly determine the definite
integral of f(x) from 0 to p/2
4- Determine and plot a function A(z) representing the
general area under f from 0 to any arbitrary point z
)
2
sin(
)
( x
x
f 


2
/
0
2 )
(

 dx
x
f
A

 dx
x
f
x
F )
(
)
(


z
dx
x
f
z
A
0
)
(
)
(
125
Indefinite Closed form
Matlab can be used to verify the integral pair shown on a previous slide
The integration variable parameter does not need to be specified since x
is the only variable in the expression, hence it will be the default variable
of integration
» syms x
» f=(sin(2*x));
» F=int(f)
F =
sin(x)^2 - 1/2
)
2
sin(
)
( x
x
f 
2
1
sin
)
(
)
( 2


 x
x
f
x
F
126
Definite Integral Evaluation
The definite integral can be evaluated from the
indefinite integral using the relationship:
Considering the previous function:
» Fb=subs(F,'x',pi/2)
Fb = ?
» Fa=subs(F,'x',0)
Fa = ?
» A_pidiv2 = Fb - Fa
A_pidiv2 = ?
)
(
)
(
)
( a
F
b
F
dx
x
f
b
a



?
)
2
/
( 

F
1
)
2
sin(
2
/
0
2 
 

 dx
x
A
2
1
sin
)
( 2

 x
x
F
?
)
0
( 
F
127
Since f(x) has a closed form, the int command can be used to directly
determine the definite integral
Matlab Direct Evaluation
» f=(sin(2*x));
» F_definite=int(f,0,pi/2)
F_definite =
?
1
)
2
sin(
2
/
0
2
/ 
 

 dx
x
A
128
A general function, A(z), used to plot the area under the curve f(x) to an
arbitrary point z can be determined as follows:
Area Under Curve
» syms z
» F_z = subs(F,x,z);
» F_0 = subs(F,x,0);
» A_z = F_z - F_0
A_z = ?
» A_z_pidiv2=subs(A_z,z,pi/2)
A_z_pidiv2 = ?
129
Multiple Independent Variables Example
Given the function f(t,x,y):
Use Matlab to determine the closed
form integrals with respect to the
different independent variables:
1-Integrate f with respect to t :
2-Integrate f with respect to x :
3-Integrate f with respect to y :
txy
tx
t
y
x
t
f 3
2
)
,
,
( 



 dt
y
x
t
f
t
F )
,
,
(
)
(

 dx
y
x
t
f
x
F )
,
,
(
)
(

 dy
y
x
t
f
y
F )
,
,
(
)
(
130
Integrating with respect to the default independent variable will integrate
with respect to x
Default Integration
» syms t x y
» f=sym('t + 2*t*x + 3*x*y*t');
» Fx = int(f)
Fx = ?
131
Integration of f(t,x,y) with respect to t or y must be explicitly specified as an
input argument to int
Other Independent Variables
» Ft=int(f,t)
Ft = ?
» Fy=int(f,y)
Fy = ?
132
Numerical Integration
Some functions do not have closed form integrals
A definite integral can be numerically approximated provided that the
function is defined over the region of interest
Numerical integration is performed by:
Dividing the integration region into very small regions
Approximating the area in each region
Summing the areas.
If the length of the subintervals tends to 0 and the sum of areas tends to
a unique limit, I, the definite integral over the interval is I
133
quad Command
The quad command is used to numerically evaluate an integral
Q = quad('f',a,b) approximates the integral of f(x) from a to b
'f' is a string containing the name of an m-function to be integrated.
Function f must return a vector of output values when given an input
vector.
Q = Inf is returned if an excessive recursion level is reached, indicating a
possibly singular integral.
Typically, a new m-function needs to be created for f when numerically
evaluating an integral
134
Numerical Integration Example
Given the function, f(x):
and The definite integral, F:
1-Use the symbolic toolbox to verify that the f(x) does not have a closed
form indefinite integral
2-Plot f(x) to ensure that the function is continuously defined over the
integration region
3-Numerically integrate f(x) to determine F
2
)
sin(
)
( x
e
x
x
f 



2
0
)
(

dx
x
f
F
135
Solution (1/3): No Closed form
Verify the closed form absence using Matlab’s symbolic toolbox:
» syms x;
>>f_sym = sin(x)*exp(-x^2);
» int(f_sym)
ans = ?
136
The plot confirms that
f(x) is continuous over
the integration region
 Numerical integration
is possible
» ezplot(f_sym)
» grid on
Solution (2/3): Continuous Plot
2
0


Continuous
137
Solution (3/3): Numerical Integration
Must numerically evaluate the integral using the quad command which
requires a function as an input
Create a new m-function describing the function:
The function must return a vector so be sure to use .* and .^ notations
where appropriate
function f = f_sin_exp_sqr( x )
f=sin(x).*exp(-x.^2);
2
)
sin(
)
( x
e
x
x
f 

138
Use the quad command to perform the numerical integration and evaluate
the definite integral
Solution (3/3): Numerical Integration
» F_num_int = quad('f_sin_exp_sqr',0,pi/2)
F_num_int =
?
139
Closed Form and Numerical Integration Example
Given the function f(x):
The definite integral, F:
1-Plot f(x) to ensure that the function is continuously defined over the
integration region
2-Use the symbolic toolbox to evaluate the definite integral
3-Numerically integrate f(x) to determine the definite integral
)
(
tan
)
( 1
x
e
x
f x 




4
0
)
( dx
x
f
F
140
Use ezplot to plot the
function
» syms x
» f_sym=exp(x)+atan(x);
» ezplot(f_sym)
» grid on
Continuity confirmed in
the x = [0,4] interval
Solution (1/3): Continuous Plot
141
Use the symbolic toolbox int command to evaluate definite integral from the
closed form integral
Solution (2/3): Symbolic Evaluation
» defint_sym=int(f_sym,0,4);
defint_sym =
?
>>defint_dbl=double(f_sym)
defint_dbl =
?
142
Solution (3/3): Numerical Evaluation
Create a new m-function to represent f(x):
function f = f_exp_atan( x )
f=exp(x)+ atan(x);
Use quad command to numerically evaluate the definite integral and
verify the previous symbolic result
» defint_numint=quad('f_exp_atan',0,4)
defint_numint = ?
Small difference to numerical approximation
Summary
Definite integrals are evaluated over a continuous
interval and result in a number
Closed form indefinite integral functions exist for
some functions independent of the integration
limits
The definite integrals can be evaluated from the
closed form indefinite integral if it exists
If a closed form indefinite integral does not exist,
the definite integral of continuous functions can
still be numerically approximated
Chapter 6: Symbolic Math in MATLAB
Slim Chtourou
Lecturer
slim.chtourou@ieee.org
www.slim.fr.mu
Outline
Creating Symbolic Variables
Defining Symbolic Expressions
Using factor command
Using collect command
Solve mathematical equations
146
The factor(f) command factors f into polynomial products
factor Command
» syms x
» f=x^3+4*x^2-11*x-30
» y = factor(f)
y = ?
» y = factor(x^5-1)
y =
(x-1)*(x^4+x^3+x^2+x+1) )
1
)(
1
(
1 2
3
4
5






 x
x
x
x
x
x
147
collect Comand
The collect command collects coefficients of a symbolic expression and
rewrites it as powers of a polynomial
collect(s,v)
s is a symbolic expression matrix
v is the independent polynomial variable
If v is omitted, collect uses rules to determine a default variable
148
» syms x t
» f=(1+x)*t+x*t
f_col_x = collect(f,x)
f_col_x = ?
» f_col_t = collect(f,t)
f_col_t = ?
» f_col = collect(f)
f_col = ?
Examples:
-Create symbolic expression
f(x,t)=(1+x)t+xt
-Specify collecting the x terms
-Specify collecting the t terms
-Unspecified independent
variable collects the x variable
Part 2: Solving Algebraic Equations
with Multiple Variables
Outline
Solve Command for Equations of Multiple
Variables
Single Equation of Two Variables Example
Two Variable Complex Solution Example
System of Equations Example
151
Solve Command for Equations of Multiple Variables
The solve command can be used to solve symbolic expressions with
more than one variable:
solve(f) solves the symbolic expression f using the symbolic variable
closest to x as the independent variable
solve(f, v) solves the symbolic expression f in terms of the independent
variable v
152
Single Equation of Two Variables Example
Given the equation
1- Find the solution of the equation assuming that c is the solution variable
2- Find the solution of the equation assuming that b is the solution variable
0
2
4
2


 b
c
b
153
Solve for b as the independent
variable
b must be explicitly specified on the
command line
sol_b=solve(f,b)
sol_b =
[ -1+(1-4*c)^(1/2)]
[ -1-(1-4*c)^(1/2)]
» syms b c
» f=b^2+4*c+2*b;
» sol_c=solve(f)
sol_c =
-1/4*b^2-1/2*b
0
2
4
2


 b
c
b
2
4
2
b
b
c 


c
b
c
b
4
1
1
4
1
1
2
1








154
Two Variable Complex Solution Example
Given the equation of two variables:
x2
+ 9y4
= 0
Solve for x in terms of y using Matlab:
» syms x y
» xs=solve(x^2+9*y^4)
xs =
[ 3*i*y^2]
[ -3*i*y^2]
Roots are
Complex Conjugates
155
Matlab Command window:
>> syms x
>> f=2*x^2 + 4*x -8;
>> solve(f,x)
ans = ?
Alternately, you may use the following lines in
Matlab to perform the same calculation:
>> f=[2 4 -8];
>> roots(f)
ans = ?
Are the results the same?
Example: finding roots
Solve the following equation with 2
methods:
F(x)=2x² + 4x - 8

More Related Content

PDF
Matlab tutorial 4
DOCX
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
PPTX
3_MATLAB Basics Introduction for Engineers .pptx
PDF
Lecture 01 variables scripts and operations
PDF
Introduction to matlab
PDF
Introduction to matlab
PPTX
1. Ch_1 SL_1_Intro to Matlab.pptx
PPT
MatlabIntro1234.ppt.....................
Matlab tutorial 4
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
3_MATLAB Basics Introduction for Engineers .pptx
Lecture 01 variables scripts and operations
Introduction to matlab
Introduction to matlab
1. Ch_1 SL_1_Intro to Matlab.pptx
MatlabIntro1234.ppt.....................

Similar to matlab presentation fro engninering students (20)

PPT
MatlabIntro (1).ppt
PDF
A complete introduction on matlab and matlab's projects
PPT
WIDI ediot autis dongok part 2.ediot lu lembot lu
PPT
WIDI ediot autis dongok part 3.EDIOT LU LEMBOT LY
PPT
WIDI ediot autis dongok part 1.ediot lu lemot lu setan lu
DOCX
More instructions for the lab write-up1) You are not obli.docx
PPTX
Chap#0_Introducation_to_nsnsnnMATLAB.pptx
PPT
matlabchapter1.ppt
PPT
WIDI FREAK MANUSIA SETENGAH EDIOTDAN LEMBOT
PPT
MatlabIntro.ppt
PPT
MatlabIntro.ppt
PPT
MatlabIntro.ppt
PPT
Matlab intro
PPT
MatlabIntro.ppt
PPT
Introduction to matlab
PPT
MATLAB-Introd.ppt
PPTX
Introduction to MATLAB Programming for Engineers
PPTX
intro2matlab-basic knowledge about Matlab.pptx
PPT
Matlab Basic Tutorial
MatlabIntro (1).ppt
A complete introduction on matlab and matlab's projects
WIDI ediot autis dongok part 2.ediot lu lembot lu
WIDI ediot autis dongok part 3.EDIOT LU LEMBOT LY
WIDI ediot autis dongok part 1.ediot lu lemot lu setan lu
More instructions for the lab write-up1) You are not obli.docx
Chap#0_Introducation_to_nsnsnnMATLAB.pptx
matlabchapter1.ppt
WIDI FREAK MANUSIA SETENGAH EDIOTDAN LEMBOT
MatlabIntro.ppt
MatlabIntro.ppt
MatlabIntro.ppt
Matlab intro
MatlabIntro.ppt
Introduction to matlab
MATLAB-Introd.ppt
Introduction to MATLAB Programming for Engineers
intro2matlab-basic knowledge about Matlab.pptx
Matlab Basic Tutorial
Ad

Recently uploaded (20)

PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPT
Project quality management in manufacturing
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPT
Mechanical Engineering MATERIALS Selection
PPTX
OOP with Java - Java Introduction (Basics)
DOCX
573137875-Attendance-Management-System-original
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
Construction Project Organization Group 2.pptx
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
PPT on Performance Review to get promotions
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Project quality management in manufacturing
Embodied AI: Ushering in the Next Era of Intelligent Systems
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Foundation to blockchain - A guide to Blockchain Tech
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Mechanical Engineering MATERIALS Selection
OOP with Java - Java Introduction (Basics)
573137875-Attendance-Management-System-original
Model Code of Practice - Construction Work - 21102022 .pdf
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Construction Project Organization Group 2.pptx
Lecture Notes Electrical Wiring System Components
CYBER-CRIMES AND SECURITY A guide to understanding
PPT on Performance Review to get promotions
bas. eng. economics group 4 presentation 1.pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Ad

matlab presentation fro engninering students

  • 1. ENG105 Engineering and Computing Skills Author image here
  • 2. Outline Chapter 1: Introduction to Matlab Chapter 2: Algorithmic Structures in MATLAB Chapter 3: Mathematical Applications in MATLAB Chapter 4: Polar Coordinates in MATLAB & Integration Using Polar Coordinates Chapter 5: Definite and Indefinite Integrals Chapter 6: Symbolic Math in MATLAB
  • 3. Chapter 1: Introduction to Matlab Author image here
  • 4. Outline Introduction Matlab for Windows Variables Matlab as a Calculator Constants and Math Functions Display Function & Formats Plots Programming in Matlab Scripts Functions
  • 5. 5 A program for doing numerical computation. Originally designed for solving linear algebra type problems using matrices. Matlab
  • 7. 7 Desktop menus File menu New Create new Matlab program file (m-file) Open existing m-file Import data Set path Open recent m-files Matlab GUI
  • 8. 8 Edit Menu Copy, cut, paste Find and replace phrases Clear command history, workspace Desktop Menu Change appearance of desktop Select windows to display MATLAB GUI
  • 9. 9 Getting Help type one of following commands in the command window: help  lists all the help topic help command  provides help for the specified command Example: >> help sqrt SQRT Square root. SQRT(X) is the square root of the elements of X. Complex results are produced if X is not positive. help help  provides information on the help command use
  • 10. 10 Variables Variables are named memory locations that can be assigned a value by the user or programmer. The system can retrieve , or “remember” the value of a variable. Variable names: Must start with a letter May contain only letters, digits, and the underscore “_” Matlab is case sensitive, i.e. one & OnE are different variables. Assignment statement: Variable = number; Variable = expression; NOTE: when a semi-colon ”;” is placed at the end of each command, the result is not displayed.
  • 11. 11 Variable Examples >> tutorial = 1234; >> tutorial = 1234 tutorial = ? >> a  ??? Undefined function or variable 'a'. >> a=2 a = ? >> a+3 ans = ? >> sqrt(a+14) ans = ? >> a=a+12 a = ?
  • 12. 12 String Variables >> a = 'This is a string' a = ? >> b= 'Another string' b = ? >> a + b  ??? Error using ==> plus Matrix dimensions must agree.
  • 13. 13 Special Variables ans : default variable name for the result pi: π = 3.1415926………… eps: ԑ = 2.2204e-016, smallest amount by which 2 numbers can differ. Inf or inf : ∞, infinity NaN or nan: not-a-number
  • 14. 14 Defining Symbolic Variables & Viewing Variables Use sym to create a symbolic variable x: Use syms to create several symbolic variables at one time Use who to view all variables in the workspace » x=sym('x'); » syms y a b » who Your variables are: Use whos to view all workspace variables with their associated size, bytes, and class information » n=1.0;t=[1.1 2.2 3.3]; » whos
  • 15. 15 Symbolic Expressions Symbolic expressions are expressions that contain symbolic variables Example: » f = 2*x^2 + x + 1; » g = a*x^2 + b*x + 5 g =?
  • 16. 16 MATLAB as a Calculator MATLAB can be used as an expression evaluator. For example, to “evaluate” pi type >> pi ans = ? x=pi % the value of pi is assigned to variable x Try the following examples: >> r = sqrt(9) r = ? >> m = sin(pi/2) m = ?
  • 17. 17 Arithmetic Operators in MATLAB The contents of all bracketed expressions are evaluated, starting from the innermost brackets and working out. All exponentials are evaluated, working from left to right. All multiplications and divisions are evaluated, working from left to right. All additions and subtractions are evaluated, working from left to right. Operators: + for addition - For subtraction * for multiplication / for division ^ for power
  • 18. 18 Operator Precedence Precedence is the order in which operations are performed. (Highest) Parenthesis . anything in parenthesis is done first Exponentiation Multiplication, division (Lowest) Addition, subtraction Spaces are ignored Solve the following examples: >> 2 + 3 * 4 >> 2 * 3 ^ 2 >> (2 + 3) * 4 >> (2^(2 + 3)) * 4
  • 19. 19 Constants and Functions >> eps ans = 2.2204e-016 >> sin(pi/2) ans = 1 >> log(1000) ans = 6.9078 >> log10(1000) ans = 3
  • 20. 20 Elementary Math Functions >> help elfun Elementary math functions. Trigonometric. sin - Sine. sinh - Hyperbolic sine. asin - Inverse sine. asinh - Inverse hyperbolic sine. cos - Cosine. cosh - Hyperbolic cosine. acos - Inverse cosine. acosh - Inverse hyperbolic cosine. tan - Tangent. tanh - Hyperbolic tangent.
  • 21. 21 Elementary Math Functions exp Exponential (e^x). log Natural logarithm. log10 Common (base 10) logarithm. log2 Base 2 logarithm and dissect floating point number. sqrt Square root. Exponential function examples: >> exp(log(3)) >> log(exp(3)) >> log2(32) >> log2(pow2(5))
  • 22. 22 Elementary Math Functions Rounding and remainder fix Round towards zero. floor Round towards minus infinity. ceil Round towards plus infinity. round Round towards nearest integer. mod Modulus (signed remainder after division). rem Remainder after division. sign Signum.
  • 23. 23 Rounding Examples + round(2.7) = ? round(2.3) = ? fix(2.3) = ? fix(2.7) =? ceil(2.3) = ? ceil(2.7) = ? floor(2.3) = ? floor(2.7) = ? - round(-2.7) = ? round(-2.3) = ? fix(-2.3) = ? fix(-2.7) = ? ceil(-2.3) = ? ceil(-2.7) = ? floor(-2.3) = ? floor(-2.7) = ?
  • 24. 24 Mathematical Functions in MATLAB Some of the Matlab built-in functions are: abs(x) for absolute value sqrt (x) for square root sin(x) for sine cos(x) for cosine tan(x) for tangent cot(x) for cotangent log(x) for natural logarithm exp(x) for exponentioal atan(x) for inverse tangent or arctan sinh(x) for sine hyperbolic
  • 25. 25 disp Function Used to display numbers and strings. The values displayed at the screen don’t necessarily include all the information. It is possible to change the display format. Examples >> disp(3)  3 >> disp('abc')  abc >> format long >> pi  ans = ? >> format short >> pi  ans = ?
  • 26. 26 fprintf Function Advanced version of the disp dunction Displays text and variables simultaneously C++ principles based Syntax: fprintf(‘text %var1_place_type text’, var1_name) Example: a=65; b=97; fprintf('the sum of %i and %i is %i',a,b,a+b) fprintf('the ASCII code of %s is %i',a,a)
  • 27. 27 fprintf arguments Type of variables: %i: integer %d: double %f: float %c: char %s: string Possibility to control the number of decimal places Ex: fprintf(‘a with three decimal places: %.3f',a) Ex: fprintf('a with 4 numbers: %.4i',a) All the text in the same line? Use n for a new line
  • 28. 28 Drawing in MATLAB Possibility to draw figures and curves in MATLAB The x axis limit need to be specified most of the time  ex: x= -6 : 0.1 : 6 Different plot types: Plot: draw the curve of an equation that depends on a variable Ezplot: plot with a predefined range of [-2π, 2π] Subplot: draw many plot in the same window Figure: create a separate window for a new plot Ex: syms x ezplot(sin(x)) figure ezplot(cos(x))
  • 29. 29 plot Command Syntax Plot(x,y,’r’): plot x in function of y with the ‘r’ (red style) ‘r’: red ‘b’:blue ‘black’: black ‘x’: cross ‘o’: circle ‘.’: Points plot(x,y1,'--',x,y2,'-',x,y3,':')  plot multiple plots xlabel(‘name'):  give a name to X-axis ylabel(‘name'):  give a name to Y-axis legend(‘y1',‘y2',‘y2')  display each plot’s legend title(‘name')  display the plot title axis([0 2*pi -3 3]):  define the X & Y axis limits hold on  multiple displays in 1 plot
  • 30. 30 In Matlab, we can plot a symbolic function over one variable by using the ezplot function. Plotting Symbolic Function >> syms a b c x % define symbolic math variables >> y = sin(x) >> ezplot(y) >> f = sin(x); >> ezsurf(f) % another type of plotting example >> g = cos(y); >> ezsurf(f+g);
  • 31. 31 Draw multiple independent plots in the same window Syntax: subplot(x,y,id) subplot Command syms x subplot(2,2,1) ezplot(cos(x)) subplot(2,2,2) ezplot(sin(x)) subplot(2,2,3) ezplot(tan(x)) subplot(2,2,4) ezplot(atan(x))
  • 33. 33 Script and Functions: Script Files A user-created file with a sequence of MATLAB commands in it. A text file containing script or function or program to run The file must be saved with a ‘.m’ extension to its name, thereby, making it an M-file. Executed by typing its name (without the ‘.m’ extension) at the command prompt.
  • 34. 34 Create a .m File From the File menu, select New M-File. → A new edit window should appear.
  • 35. 35 Example 1: in Command window >> example1 C = ? Example 1 in m-file: A= 2; B=3; C=A+B Save as a file name example1.m
  • 36. 36 Find the force if the mass is 10 Kg and the acceleration is 100m/sec2. Newton’s Law: F = m .γ (Force = mass x acceleration) (γ = 100) Example 2 Create a new script (example2.m) m = 10; gamma = 100; Force =m * gamma To run the above file, type in the command window >>example2
  • 37. 37 Script and Functions: Function Files A m-file also , like a script file, except that the variables are all local. A function file begins with a function definition line containing a well- defined list of inputs and outputs. Without that line, the file becomes a simple script file. The syntax of the function definition line is: function [ output variables ] = function_name ( input variables ); It is recommended for the function_name to be the same as the filename (without the ‘.m’ extension) in which the function is written. Example: if the name of the function is projectile it must be written and saved in a file with the name projectile.m.
  • 38. WARNING! for the scipt or function name file, avoid using the name of a MATLAB command such as plot, sqrt, abs…
  • 39. 39 Write a MATLAB function called sumy that adds two input numbers and returns the result minus 2 Example 3 function out = sumy(x,y) out=x+y-2 Save with filename sumy.m , then type in the command window: >>sumy(6,5) % 6 and 5 are arbitrary values chosen by the user out = ?
  • 40. 40 Solution Function file: function [area, volume] = cyl(h, r) % function to compute the area and volume of a cylinder base = pi * r^2; volume = base * h area = 2*pi*r * h + 2*base Store the function in cyl.m, then, in command window: >> cyl(6, 4) area = ? vol = ? Example 3: Measuring a Solid Object We need to compute the volume and surface area of this cylinder object: Formulas: b: base, h: height Base: b= π r² Volume = b h Area=2 π r h + 2 b
  • 42. 42 Create a m-file and enter the following statements in the m-file: A = [1 2 3; 3 3 4; 2 3 3]; b = [1; 1; 2]; x = Ab Save the file, (e.g. example1.m) In the command line, type: >> example1 x = ? Example 1: Consider the system of equations: x + 2y + 3z = 1 3x + 3y + 4z = 1 2x + 3y + 3z = 2 Find the solution x to the system of equations.
  • 43. 43 Create a file, say example2.m, which contains the following commands: x = 0:pi/100:2*pi; y1 = 2*cos(x); y2 = cos(x); y3 = 0.5*cos(x); plot(x,y1,'--',x,y2,'-',x,y3,':') xlabel('Range') ylabel('Cosine functions') legend('2*cos(x)','cos(x)','0.5*cos(x)') title('Example of multiple plots') axis([0 2*pi -3 3]) Run the file by typing example2 in the Command Window. Example 2: Plot the following cosine functions, y1 = 2 cos(x) y2 = cos(x) y3 = 0.5 * cos(x) in the interval 0  x  2.
  • 44. 44 game1 = input('Enter the points scored in the first game '); game2 = input('Enter the points scored in the second game '); game3 = input('Enter the points scored in the third game '); average = (game1+game2+game3)/3 The following shows the command prompt when this script file (saved as example3) is executed. >> example3 >> Enter the points scored in the first game xx >> Enter the points scored in the second game yy >> Enter the points scored in the third game zz average = ? Example 3: Create a script file that calculates the average of points scored in three games. The point from each game are assigned to a variable by using the ’input’ command.
  • 45. 45 Create a script in a file computes area of triangle Example 4 b=5; h=3; area=0.5*(b*h) area = ?
  • 46. 46 Scripts VS Functions To calculate the area of another triangle using the same script, it is possible to update the values of b and h in the script and re-run it. the script stores the result each time in a variable named a that is in the base workspace. Instead of manually updating the script each time, it is possible to make a more flexible program by converting the script to a function. Replace the statements that assign values to b and h with a function declaration statement. The declaration includes the function keyword the names of input and output arguments the name of the function.
  • 47. 47 Redo example 4 using the function method Example 5 function a = triarea(b,h) a = 0.5*(b.* h); After saving the file, call the function with different values a1 = triarea(1,5) a1 = ? a2 = triarea(2,10) a2= ? a3 = triarea(3,6) a3= ?
  • 48. Functions have their own workspace (local), separate from the base workspace (global). So, none of the calls to the function triarea overwrite the value of a in the base workspace. Instead, the function assigns the results to variables a1, a2, and a3.
  • 49. 49 HOMEWORK 1 Page no: 28 problem no:9&11 Page no: 30 problem no:21 Page no: 31 problem no:27 Page no: 164 problem no:6 Submit- next week class
  • 50. Chapter 2: Algorithmic Structures in MATLAB Slim Chtourou Lecturer slim.chtourou@ieee.org www.slim.fr.mu
  • 51. Outline For: iterative statement Iterative applications Taylor series If: conditional statement Conditional applications
  • 52. 52 The for loop The general form of for loop is: for i=beginning :step: final program statements end Where beginning, step, and final are integers or real numbers. Example 1: Find the sum of the integers from 5 to 100.
  • 53. 53 Solution Open an m file (example1.m) sum=0; for i=5:100 sum=sum+i; end disp(‘sum’) disp(sum) To run the above file, type in the command window >>example1
  • 54. 54 Find the sum of the odd integers between 1 and 100. Example 2 sum=0; for i=1:2:100 sum=sum+i; end disp(‘sum of odd integers between 1 and 100 is:’); disp(sum)
  • 55. 55 Find the sum of the first 10 terms as below. Example 3 sum=0; for i=1:10 sum=sum+1/i; end disp(‘sum of the 10 terms is:’); disp(sum) 10 1 9 1 8 1 7 1 6 1 5 1 4 1 3 1 2 1 1         
  • 56. 56 Functions (reminder) The general form of a function in MATLAB is function [rv1 rv2 … rvn]=Function_Name(pv1,pv2,..,pvn) where rv1, rv2,.. are the outputs pv1, pv2,.. are the inputs. The body of the function will contain the relations between the outputs and inputs.
  • 57. 57 Write a function “sumN” that finds the sum of the first N term of the series below. Example 4 function s=sumN(N) s=0; for i=1:N s=s+1/i; end To run this function code, type in the command window: >>sumN(5); N 1 .... 8 1 7 1 6 1 5 1 4 1 3 1 2 1 1         
  • 58. 58 Write a function “expN” that finds the sum of the first N term of the series below for a given value of x. Example 5 function s=expN(N,x) s=0; for i=0:N s=s+x^i/factorial(i); end In the command window: >>p=expN(5,1);   N i i i x 0 !
  • 60. 60 if statement Conditional statement are used to perform certain task if certain conditions are met or not The general structure of if statement is: if expression statements elseif expression statements else statements end
  • 61. 61 n1=input('enter number1 '); n2=input('enter number2 '); if n1>n2 disp(n1) else disp(n2) end Example 1 Create a program that accepts two numbers and display the bigger one
  • 62. 62 n1=input('enter number1 '); n2=input('enter number2 '); if n1>n2 disp('n1>n2') elseif n1<n2 disp('n1<n2') else disp('the numbers are identical') end Example 2 Create a program that compares two numbers inputted by the user and display the comparison result
  • 63. 63 nrows = 6; ncols = 6; A = ones(nrows,ncols) for c = 1:ncols for r = 1:nrows if r == c A(r,c) = 2; elseif abs(r-c) == 1 A(r,c) = -1; else A(r,c) = 0; end end end A Example 3 1-Create a matrix and fill it with 1 2-Loop through the matrix and assign each element a new value: 2 on the main diagonal -1 on the adjacent diagonals 0 everywhere else.
  • 64. 64 syms hw pr mt et total nbr=input('enter the number of student ') for i=1:nbr fprintf('student %in',i) hw(i)=input('enter the homework grade '); pr(i)=input('enter the project grade '); mt(i)=input('enter the midterm exam grade '); et(i)=input('enter the endterm exam grade '); end for i=1:nbr moy(i)=hw(i)+pr(i)+mt(i)+ et(i); end for i=1:nbr if moy(i)<60 fprintf('student %i got %d, so he has failedn',i,moy(i)) else fprintf('student %i got %d, so he has passedn',i,moy(i)) end end Example 4 Create a program that collects the n students’ grades (Homework, Project, mid-term & End-term) and determines if the student has passed or failed the course
  • 65. Homework 2 Redo the previous example while taking all possible grades (F, D, D+, C, C+, B, B+, A & a+) into account
  • 66. Chapter 3: Mathematical Applications in MATLAB Slim Chtourou Lecturer slim.chtourou@ieee.org www.slim.fr.mu
  • 68. 68 Matlab can also compute many integrals and derivatives that you might find in Calculus or many advanced engineering courses. The key functions are int for integration and diff for derivation. Derivation and Integration >> syms x; >> f = sin(5*x) >>diff(f) ans = ?
  • 69. 69 Derivation and Integration (2nd and Higher Derivative) >> f = x^3 >> diff(f) % 1st derivative ans = ? >> diff(f,2) % 2nd derivative ans = ? >> diff(f,3) % 3rd derivative ans = ? >> diff(f,4) % 4th derivative ans = ?
  • 70. 70 Partial Differential Equations Sometimes, an expression can have multiple variables. To compute the derivative of the function with respect to one variable, use a second parameter to the diff function: >> syms x t; >> f = sin( x * t ) >> diff(f,t) % derivative of f with respect to t ans = ?
  • 71. 71 By using the int function, in the same way we use the diff function, we can ask Matlab to do symbolic integration for us. Integration >> syms x t; >> f = x * x ; >>int(f) ans = ?
  • 72. 72 As you (should) know, a definite integral represents the area under a curve from a given start point to a given end point. Try to find how much area is under the curve f(x) = x^3; for [0..10], [-10..10], [- 10..0] Definite Integrals >> syms x; f= x^3 >> int(x^3,0,10) ans = ? >> int(x^3,-10,10) ans = ? >> int(x^3,-10,0) ans = ?
  • 73. MATLAB can find the derivative of symbolic expressions. Higher derivatives can also be found easily. These derivatives can be evaluated for arbitrary values of the independent variable.
  • 74. 74 Enter: syms x g = x^2*cos(x) Now enter: diff(g, x) Then enter: diff(g, x, 2) How would you calculate the third derivative? Example:1 First we declare x to be a symbolic variable and define g to be the function given by g(x) = x2 cos(x).
  • 75. 75 Example 2 To calculate the derivative of an expression that you have not yet entered, just replace g by the expression. For example, enter: diff(x^3-x^2+2, x) Now insert a symbolic constant a into the expression. Enter: syms a diff(x^3 - a*x^2 + 2, x) Then change the final x to an a. That is, enter: diff(x^3 - a*x^2 + 2, a) What is the role of the symbol after the comma in the differentiation expression?
  • 76. 76 Example 3 Evaluate the derivative dg/dx at x = 2.1. Enter: gp=diff(g, x) Then enter: subs(gp, x, 2.1) Alternatively, you could enter: subs( diff(g, x), x , 2.1 )
  • 77. Check your understanding so far by using MATLAB to calculate the second derivative of tan(x6 - 3x + 5) at x = 3/2.
  • 78. 78 Calculate the derivative of the function F(x)=x3 - cos(x) Example 4 >> syms x >> f=x^3-cos(x); >> g=diff(f) g = ?
  • 79. 79 Obtain the derivative of the following function according to y: F(x,y)=x² +(y+5)3 Example 5 Matlab command entries: >> syms x y >> f=x^2+(y+5)^3; >> diff(f,y) ans = ? Note that in this case, the command diff(f,y) is equivalent to
  • 80. 80 Find the derivative of f(x)=sin(ex ). Example 6 >> syms x >> f=sin(exp(x)); >> diff(f) ans = ?
  • 81. 81 To compute the partial derivative of an expression with respect to some variable we specify that variable as an additional argument ‘diff’ f(x,y)=x3 y4 +ysin(x) Example 7 >> syms x y >> f=x^3*y^4+y*sin(x) >> diff(f,x) ans = ? >> diff(f,y) ans = ?
  • 82. 82 Taylor Series The Taylor series is a representation of a given function as an infinite sum of terms calculated from its derivatives values at a single point. If the series is centered at zero, the Taylor series is Maclaurin series. It is a common practice to use a finite number of terms to approximate the function. Taylor series of order 5 is an approximation of f(x) as a polynomial of degree 5. The general expression of Taylor series for an analytic function f(x) about the base point x=a is: fm (a) is the mth derivative of f(x) at the point a.      0 ! ) ( ) ( ) ( m m m m a a x x f f
  • 83. 83 Use the "taylor" function to create a taylor series Taylor Command >> syms x >> f = taylor(log(1+x)) f = ?
  • 84. 84 Taylor Series Two methods for MATLAB to find the Taylor series expansion of f(x) at x=a Method 1: Using the general Taylor series summation and programming it using function and for loops as explained in the example 5. Method 2: Using the MATLAB function : taylor, In general: taylor(f,n,a) returns the Taylor series expansion of f(x) of order n-1 at the base point x=a. taylor(f,n) returns the Taylor series expansion of f(x) of order n-1 at the base point x=0. taylor(f,a) returns the Taylor series expansion of f(x) of order 5 at the base point x=a. Note: f must be a symbolic expression representing f(x)
  • 85. 85 Example 8 Given a function f(x)=sin(x). Write a program that finds the Taylor series expansion of f(x) at x=0 of degree 3. Plot f(x) and its Taylor series approximation of degree 3 on the same graph for x in the range [-pi,pi] Add Taylor series of degrees 5, 7 to the same plot. Which Taylor series better approximates f(x). What is your conclusion?
  • 86. 86 Solution (1/2) Open a script file example6.m syms x; f=sin(x); t3=taylor(f,4); %Taylor series at x=0 of degree 3 xd=-pi:pi/20:pi; yd=subs(f,x,xd); %This evaluates f(x) at xd (symbolic). td3=subs(t3,x,xd); %This evaluates t(x) at xd. plot(xd,yd,’y’); hold on; plot(xd,td3,’m’);
  • 87. 87 t5=taylor(f,6); %5th deg Taylor series at x=0 t7=taylor(f,8); %7th deg Taylor series at x=0 td5=subs(t5,x,xd); td7=subs(t7,x,xd); plot(xd,td5,’r’); hold on; plot(xd,td7,’b’); Legend(‘exact’,’Taylor 3’,’Taylor 5’,’Taylor 7’); xlabel(‘x’); ylabel(‘function’) Solution (2/2)
  • 88. 88 syms x; f=sin(x); t3=taylor(f,4); %3rd deg Taylor series at x=0 f_inline=inline(char(f)); %f:symbolic  function t3_inline=inline(char(t3)); fplot(f_inline,[-pi ,pi],'b'); hold on; fplot(t3_inline,[-pi, pi],'r'); Legend('exact','Taylor 3'); xlabel('x'); ylabel('function') Example 8(Another Method)
  • 89. 89 Find the following integration using Taylor series of order 6: Example 9 syms x; f=exp(x^2); t6=taylor(f,7); %Taylor series at x=0 of degree 6 int(t6,-1,1) %Integration of t6 Ans= ? dx ex   1 1 2
  • 90. 90 Example 9 Solution (2nd Method) (1/3) The series expansion of ex is known: The series expansion of ex2 can then be found by replacing x with x² The integration of ex 2 can then be found     0 ! i i x i x e         0 2 0 2 ! ! ) ( 2 i i i i x i x i x e ) ( ) ! )( 1 2 ( ! ! 0 1 2 0 2 0 2 2 x f i i x dx i x dx i x dx e i i i i i i x                  ) 1 ( ) 1 ( 1 1 2      f f dx ex
  • 91. 91 So, this method depends on writing the MATLAB function f(x) and finding f(1) - f(-1) Example 9 Solution (2nd Method) (2/3) function s=f(x) s=0; for i=0:100 s=s+ x^(2*i+1)/((2*i+1)*factorial(i)); end In the command window, type: >> int_result=f(1)-f(-1) int_result=?
  • 92. 92 In the previous example, plot f(x) and its Taylor approximation t6(x) on the same graph for -1 ≤ x ≤ 1 syms x; f=exp(x^2); xd=-1:0.1:1; yd=subs(f,xd); plot(xd,yd,’r’); hold on; t6=taylor(f,7); %Taylor of degree 6 td=subs(t6,xd); plot(xd,td,’b’); xlabel(‘x’); ylabel(‘functions’); legend(‘f(x)’,’Taylor’) Example 9 Solution (2nd Method) (3/3)
  • 93. 93 Find the taylor series expansion of order 3 about the point x=1 of the function Example 10 syms x; f = 1/(1+x); t3 = taylor(f,4,1) T3 = ? x x f   1 1 ) (
  • 94. 94 Find the taylor series expansion of order 3 about the point x=0 of the function Example 11 syms x; f=1/(1+x); t3=taylor(f,4) t3 = ? x x f   1 1 ) (
  • 95. Chapter 4: Polar Coordinates in MATLAB & Integration Using Polar Coordinates Slim Chtourou Lecturer slim.chtourou@ieee.org www.slim.fr.mu
  • 96. Outline Converting Polar Coordinates to Rectangular Converting Rectangular Coordinates to Polar Plotting Polar Coordinates
  • 97. 97 Every point can be expressed in: Rectangulat coordinates: (x,y) Polar coordinates: (r,θ) Polar and Rectangular Coordinates
  • 98. 98 [x,y] = pol2cart(theta,r) [theta,r] = cart2pol(x,y) angle comes first Converting Between Polar And Cartesian in Matlab >>[x,y] = pol2cart(pi/4,1) x = ? y = ? >>[theta,r] = cart2pol(0,-4) theta = ? r = ?
  • 99. 99 Calculate the cartesian coordinates of the two red points • Exercise θ is expressed in radians
  • 100. 100 Polar Command in Matlab The Matlab command:  >> polar (theta,r,s); Plots the points defined in polar coordinates as (r,theta) for all values of r and theta s is a string that defines the style of the plot Ex: ‘y’: yellow | ‘r’: red Reminder: theta must be in radians
  • 101. 101 Use MATLAB to plot the following points in polar coordinates: r=5, θ=0° | r=5, θ=60° | r=3, θ=180° | r=3, θ=300° | r=3, θ=-30° Example 1 Solution: Create a script file: example1.m >> r=[5 5 3 3 3]; >> theta=[0 60 180 300 -30]*pi/180; %Convert to radians >> polar(theta , r, 'x');
  • 102. 102
  • 103. 103 Conversion Between Polar and Rectangular Polar to Rectangular X = r cosθ Y = r sinθ Rectangular to Polar r = θ = tan-1 ()
  • 104. 104 Solution: >>x=3; >>y=4; >>r=sqrt(x^2+y^2); >>theta=atan2(y,x); % in radians >>theta = theta *180/pi % in degrees Answer: r=? theta=? Example 2 Find the polar coordinates of a point (x,y) of your choice using Matlab as a calculator
  • 105. 105 Solution: >>r=5; >>theta=53*pi/180; %convert to radians >>x = r * cos(theta); >>x = r * sin(theta); Answer: x=3 y=4 Example 3 Find the rectangular coordinates of the point (5,53°) using Matlab as a calculator
  • 106. 106 Solution: Open a script file example1d.m >>r=[5 5 3 3 3]; >>theta=[0 60 180 300 -30]*pi/180;%to rad >>polar(theta,r,’x’); >>hold on; >>x=r .* cos(theta); % from polar to rectangular >>y=r .* sin(theta); % from polar to rectangular >>plot(x,y, ‘o’); Example 3 Repeat Example 1 and plot the given points using the polar to rectangular conversion relation. Add the two examples on one plot.
  • 107. 107
  • 108. 108 Using Matlab, draw the curve r = sin(θ) Example 5 Solution: Open a script file example5.m theta=linspace(0,2*pi,200); %generates 200 points between 0 and 2π r=sin(theta); polar(theta,r,’r’);
  • 109. 109
  • 110. 110 Using Matlab, draw the curve r = cos(2θ) Example 6 Solution: Open a script file example6.m >>theta=linspace(0,2*pi,200); %generates 200 points between 0 and 2π >>r=cos(2*theta); >>polar(theta,r,’r’);
  • 111. 111
  • 112. 112 Area in Polar Coordinates (from calculus II) The area bounded by the curves r1(θ) , r2(θ), θ = θ1 and θ = θ2 is given by: θ1 and θ2 must be in radians Example 7: Find the area bounded by the curves r = 2 sinθ, θ1 = 45°, θ2 = 135° and the origin Show all curves in one plot    d r r ) ( 2 1 2 1 2 2 2 1    Area
  • 113. 113 1-plot the 3 curves Open script file example7.m >>theta=linspace(0,2*pi); %or theta=0:2*pi/100:2*pi; >>r=2*sin(theta); >>polar(theta,r,’r’); %plots r=2 sin(theta) >>hold on; >>r=linspace(0,2); >>theta=(45*pi/180)*ones(size(r)); >>polar(theta,r,’b’); >>hold on; >>r=linspace(0,2); >>theta=(135*pi/180)*ones(size(r)); >>polar(theta,r,’g’); Solution (1/2)
  • 114. 114 Solution (2/2) 2-form the integration and put the limits: 3-Go to command window of MATLAB and do the integration using int: >>syms theta; >>area=eval(0.5 * int(4 * sin(theta)^2 , pi/4 , 3*pi/4)) Answer: area=?       d ) 0 sin 4 ( 2 1 4 3 4 2      Area    d r r ) ( 2 1 2 1 2 2 2 1    Area
  • 115. 115 Determine the area of the region that lies inside r= 3 +2 sinθ and r=2, show the region Solution 1-plot the two curves: Open example8.m >>theta=linspace(0,2*pi) >>r=2*ones(size(theta)); >>polar(theta,r,’r’); >>hold on; >>r=3+2*sin(theta); >>polar(theta,r); Example 8
  • 116. 116 Solution (2/2) 2-form the integration and put the limits: 3-Go to command window of MATLAB and do the integration using int: >>syms theta; >>area=eval(0.5*int((3+2*sin(theta))^2-4,-pi/6,7*pi/6)) Answer: area=?       d Area ] 4 ) sin 2 3 [( 2 1 6 7 6 2           d Area r r ) ( 2 1 2 1 2 2 2 1   
  • 117. Chapter 5: Definite and Indefinite Integrals Slim Chtourou Lecturer slim.chtourou@ieee.org www.slim.fr.mu
  • 118. Outline Definite and Indefinite Integrals Integral Pairs Closed Form Integrals Int Command Closed Form Example Multiple Independent Variable Example Numerical Integration quad Command Numerical Integration Example Closed Form and Numerical Integration Example
  • 119. 119 Definite & Indefinite Integrals A definite integral represents the area under a curve f(x) between the lower limit ‘a’ and the upper limit ‘b’ An integral is considered to be indefinite if the upper and lower limits are not specified   b a DEFINITE dx x f I ) (   dx x f IINDEFINITE ) (
  • 120. 120 Integral Pairs Some indefinite integrals can be considered of as the inverse of differentiation Common examples: Note: due to initial conditions, arbitrary integral pairs are not unique and may differ by a constant of integration, c c ax adx    c n ax dx ax n n      1 1 c a e dx e ax ax    c b bx a dx bx a    ) sin( ) cos( c b bx a dx bx a     ) cos( ) sin( c x a dx x a    ) ln(
  • 121. 121 Closed Form Integrals Closed form integrals can be expressed as explicit functions. The integral pairs on the previous slide are examples of closed form integrals. Techniques such as partial fraction expansion, integration by parts, and integration by substitution can be used to express some integrals in closed form. It is not always possible to find the closed form for the integral of an arbitrary function
  • 122. 122 Evaluation of Definite Integral If a closed form indefinite integral exists, it can be used to evaluate a definite integral over a region of integration An integral from an arbitrary lower limit to a fixed upper limit is denoted as: Thus definite integral from a lower limit a to an upper limit b can be evaluated using:   x du u f x F ) ( ) (      b x x a b a dx x f dx x f dx x f 0 0 ) ( ) ( ) ( b a b a x F a F b F dx x f ) ( ) ( ) ( ) (    
  • 123. 123 int command The int command is used to solve integrals which can be expressed in closed form int(s) returns the indefinite integral of the symbolic variable s with respect to its default symbolic variable int(s,v) returns the indefinite integral of the symbolic variable s with respect to the symbolic variable v int(s,a,b) returns the definite integral of the symbolic variable s with respect its default symbolic variable from a to b int(s,v,a,b) returns the definite integral of the symbolic variable s with respect to the symbolic variable v from a to b
  • 124. 124 Closed form Example Given the function, f(x): 1- Use the int command to determine the Closed Form Indefinite Integral, F(x): 2- From the closed form integral, F(x), determine the definite integral of f(x) from 0 to p/2 3- Use the int command to directly determine the definite integral of f(x) from 0 to p/2 4- Determine and plot a function A(z) representing the general area under f from 0 to any arbitrary point z ) 2 sin( ) ( x x f    2 / 0 2 ) (   dx x f A   dx x f x F ) ( ) (   z dx x f z A 0 ) ( ) (
  • 125. 125 Indefinite Closed form Matlab can be used to verify the integral pair shown on a previous slide The integration variable parameter does not need to be specified since x is the only variable in the expression, hence it will be the default variable of integration » syms x » f=(sin(2*x)); » F=int(f) F = sin(x)^2 - 1/2 ) 2 sin( ) ( x x f  2 1 sin ) ( ) ( 2    x x f x F
  • 126. 126 Definite Integral Evaluation The definite integral can be evaluated from the indefinite integral using the relationship: Considering the previous function: » Fb=subs(F,'x',pi/2) Fb = ? » Fa=subs(F,'x',0) Fa = ? » A_pidiv2 = Fb - Fa A_pidiv2 = ? ) ( ) ( ) ( a F b F dx x f b a    ? ) 2 / (   F 1 ) 2 sin( 2 / 0 2      dx x A 2 1 sin ) ( 2   x x F ? ) 0 (  F
  • 127. 127 Since f(x) has a closed form, the int command can be used to directly determine the definite integral Matlab Direct Evaluation » f=(sin(2*x)); » F_definite=int(f,0,pi/2) F_definite = ? 1 ) 2 sin( 2 / 0 2 /      dx x A
  • 128. 128 A general function, A(z), used to plot the area under the curve f(x) to an arbitrary point z can be determined as follows: Area Under Curve » syms z » F_z = subs(F,x,z); » F_0 = subs(F,x,0); » A_z = F_z - F_0 A_z = ? » A_z_pidiv2=subs(A_z,z,pi/2) A_z_pidiv2 = ?
  • 129. 129 Multiple Independent Variables Example Given the function f(t,x,y): Use Matlab to determine the closed form integrals with respect to the different independent variables: 1-Integrate f with respect to t : 2-Integrate f with respect to x : 3-Integrate f with respect to y : txy tx t y x t f 3 2 ) , , (      dt y x t f t F ) , , ( ) (   dx y x t f x F ) , , ( ) (   dy y x t f y F ) , , ( ) (
  • 130. 130 Integrating with respect to the default independent variable will integrate with respect to x Default Integration » syms t x y » f=sym('t + 2*t*x + 3*x*y*t'); » Fx = int(f) Fx = ?
  • 131. 131 Integration of f(t,x,y) with respect to t or y must be explicitly specified as an input argument to int Other Independent Variables » Ft=int(f,t) Ft = ? » Fy=int(f,y) Fy = ?
  • 132. 132 Numerical Integration Some functions do not have closed form integrals A definite integral can be numerically approximated provided that the function is defined over the region of interest Numerical integration is performed by: Dividing the integration region into very small regions Approximating the area in each region Summing the areas. If the length of the subintervals tends to 0 and the sum of areas tends to a unique limit, I, the definite integral over the interval is I
  • 133. 133 quad Command The quad command is used to numerically evaluate an integral Q = quad('f',a,b) approximates the integral of f(x) from a to b 'f' is a string containing the name of an m-function to be integrated. Function f must return a vector of output values when given an input vector. Q = Inf is returned if an excessive recursion level is reached, indicating a possibly singular integral. Typically, a new m-function needs to be created for f when numerically evaluating an integral
  • 134. 134 Numerical Integration Example Given the function, f(x): and The definite integral, F: 1-Use the symbolic toolbox to verify that the f(x) does not have a closed form indefinite integral 2-Plot f(x) to ensure that the function is continuously defined over the integration region 3-Numerically integrate f(x) to determine F 2 ) sin( ) ( x e x x f     2 0 ) (  dx x f F
  • 135. 135 Solution (1/3): No Closed form Verify the closed form absence using Matlab’s symbolic toolbox: » syms x; >>f_sym = sin(x)*exp(-x^2); » int(f_sym) ans = ?
  • 136. 136 The plot confirms that f(x) is continuous over the integration region  Numerical integration is possible » ezplot(f_sym) » grid on Solution (2/3): Continuous Plot 2 0   Continuous
  • 137. 137 Solution (3/3): Numerical Integration Must numerically evaluate the integral using the quad command which requires a function as an input Create a new m-function describing the function: The function must return a vector so be sure to use .* and .^ notations where appropriate function f = f_sin_exp_sqr( x ) f=sin(x).*exp(-x.^2); 2 ) sin( ) ( x e x x f  
  • 138. 138 Use the quad command to perform the numerical integration and evaluate the definite integral Solution (3/3): Numerical Integration » F_num_int = quad('f_sin_exp_sqr',0,pi/2) F_num_int = ?
  • 139. 139 Closed Form and Numerical Integration Example Given the function f(x): The definite integral, F: 1-Plot f(x) to ensure that the function is continuously defined over the integration region 2-Use the symbolic toolbox to evaluate the definite integral 3-Numerically integrate f(x) to determine the definite integral ) ( tan ) ( 1 x e x f x      4 0 ) ( dx x f F
  • 140. 140 Use ezplot to plot the function » syms x » f_sym=exp(x)+atan(x); » ezplot(f_sym) » grid on Continuity confirmed in the x = [0,4] interval Solution (1/3): Continuous Plot
  • 141. 141 Use the symbolic toolbox int command to evaluate definite integral from the closed form integral Solution (2/3): Symbolic Evaluation » defint_sym=int(f_sym,0,4); defint_sym = ? >>defint_dbl=double(f_sym) defint_dbl = ?
  • 142. 142 Solution (3/3): Numerical Evaluation Create a new m-function to represent f(x): function f = f_exp_atan( x ) f=exp(x)+ atan(x); Use quad command to numerically evaluate the definite integral and verify the previous symbolic result » defint_numint=quad('f_exp_atan',0,4) defint_numint = ? Small difference to numerical approximation
  • 143. Summary Definite integrals are evaluated over a continuous interval and result in a number Closed form indefinite integral functions exist for some functions independent of the integration limits The definite integrals can be evaluated from the closed form indefinite integral if it exists If a closed form indefinite integral does not exist, the definite integral of continuous functions can still be numerically approximated
  • 144. Chapter 6: Symbolic Math in MATLAB Slim Chtourou Lecturer slim.chtourou@ieee.org www.slim.fr.mu
  • 145. Outline Creating Symbolic Variables Defining Symbolic Expressions Using factor command Using collect command Solve mathematical equations
  • 146. 146 The factor(f) command factors f into polynomial products factor Command » syms x » f=x^3+4*x^2-11*x-30 » y = factor(f) y = ? » y = factor(x^5-1) y = (x-1)*(x^4+x^3+x^2+x+1) ) 1 )( 1 ( 1 2 3 4 5        x x x x x x
  • 147. 147 collect Comand The collect command collects coefficients of a symbolic expression and rewrites it as powers of a polynomial collect(s,v) s is a symbolic expression matrix v is the independent polynomial variable If v is omitted, collect uses rules to determine a default variable
  • 148. 148 » syms x t » f=(1+x)*t+x*t f_col_x = collect(f,x) f_col_x = ? » f_col_t = collect(f,t) f_col_t = ? » f_col = collect(f) f_col = ? Examples: -Create symbolic expression f(x,t)=(1+x)t+xt -Specify collecting the x terms -Specify collecting the t terms -Unspecified independent variable collects the x variable
  • 149. Part 2: Solving Algebraic Equations with Multiple Variables
  • 150. Outline Solve Command for Equations of Multiple Variables Single Equation of Two Variables Example Two Variable Complex Solution Example System of Equations Example
  • 151. 151 Solve Command for Equations of Multiple Variables The solve command can be used to solve symbolic expressions with more than one variable: solve(f) solves the symbolic expression f using the symbolic variable closest to x as the independent variable solve(f, v) solves the symbolic expression f in terms of the independent variable v
  • 152. 152 Single Equation of Two Variables Example Given the equation 1- Find the solution of the equation assuming that c is the solution variable 2- Find the solution of the equation assuming that b is the solution variable 0 2 4 2    b c b
  • 153. 153 Solve for b as the independent variable b must be explicitly specified on the command line sol_b=solve(f,b) sol_b = [ -1+(1-4*c)^(1/2)] [ -1-(1-4*c)^(1/2)] » syms b c » f=b^2+4*c+2*b; » sol_c=solve(f) sol_c = -1/4*b^2-1/2*b 0 2 4 2    b c b 2 4 2 b b c    c b c b 4 1 1 4 1 1 2 1        
  • 154. 154 Two Variable Complex Solution Example Given the equation of two variables: x2 + 9y4 = 0 Solve for x in terms of y using Matlab: » syms x y » xs=solve(x^2+9*y^4) xs = [ 3*i*y^2] [ -3*i*y^2] Roots are Complex Conjugates
  • 155. 155 Matlab Command window: >> syms x >> f=2*x^2 + 4*x -8; >> solve(f,x) ans = ? Alternately, you may use the following lines in Matlab to perform the same calculation: >> f=[2 4 -8]; >> roots(f) ans = ? Are the results the same? Example: finding roots Solve the following equation with 2 methods: F(x)=2x² + 4x - 8

Editor's Notes

  • #5: It’s name is derived from MATrix LABoratory. Matlab is also a programming language that currently is widely used as a platform for developing tools for Machine Learning
  • #11: tutorial = 1234 a = 2 ans = 5 ans = 4 a = 14
  • #12: a = This is a string b = Another string
  • #14: a b x y Name Size Bytes Class a 1x1 126 sym object b 1x1 126 sym object n 1x1 8 double array t 1x3 24 double array x 1x1 126 sym object y 1x1 126 sym object Grand total is 12 elements using 536 bytes
  • #15: g = a*x^2+b*x+5
  • #16: ans = 3.1416 r = 3 m = 1
  • #18: ans = 14 ans = 18 ans = 20 ans = 128
  • #21: ans = 3.0000 ans = 3 ans = 5 ans = 5
  • #22: ans = 3.0000 ans = 3 ans = 5 ans = 5
  • #23: round(2.7) = 3 round(2.3) = 2 fix(2.3) = 2 fix(2.7) =2 ceil(2.3) = 3 ceil(2.7) = 3 floor(2.3) = 2 floor(2.7) = 2 round(-2.7) = -3 round(-2.3) = -2 fix(-2.3) = -2 fix(-2.7) = -2 ceil(-2.3) = -2 ceil(-2.7) =-2 floor(-2.3) = -3 floor(-2.7) = -3
  • #25: ans = 3.14159265358979 ans = 3.1416
  • #30: y = sin(x)
  • #35: C = 5
  • #39: out = 9
  • #40: area =251.327 vol = 301.592
  • #42: x = -0.5 1.5 -0.5
  • #45: area = 7.5000
  • #47: a1 = 2.5000 a2 = 10 a3 = 9
  • #57: This will type the sum of 5 terms, and store the result in ans.
  • #58: This will produce the series sum for N=5 and x=1, and store the result in p.
  • #68: ans = 5*cos(5*x)
  • #69: ans = 3*x^2 ans = 6*x ans = 6 ans = 0
  • #70: ans = cos(x*t)*x
  • #71: ans = 1/3*x^3
  • #72: ans = 2500 ans = 0 ans = -2500
  • #77: (The value is approximately  - 4521.)
  • #78: g =3*x^2+sin(x)
  • #79: ans = 3*(y+5)^2
  • #80: ans = cos(exp(x))*exp(x)
  • #81: ans = 3*x^2*y^4+y*cos(x) ans = 4*x^3*y^3+sin(x)
  • #83: f = x-1/2*x^2+1/3*x^3-1/4*x^4+1/5*x^5
  • #89: Ans= 2.9143
  • #91: int_result=2.9253
  • #93: t3=½-1/4(x-1)+1/8(x-1)2-1/16(x-1)3
  • #94: t3=1-x+x²-x3
  • #98: X=0.7071 Y=0.7071 THETA=-1.5708 R=4
  • #104: r=5 theta=53 degrees
  • #105: x=3 y=4
  • #114: area=2.5708
  • #115: To display up to r=5, we add a 3rd curve: theta=0:0.01:6.28; r=5*ones(size(theta)); polar (theta,r,'black') hold on
  • #116: area=24.187
  • #126: Fb = 0.5000 Fa = -0.5000 A_pidiv2 = 1
  • #127: F_definite = 1
  • #128: A_z =sin(z)^2 A_z_pidiv2 = 1
  • #130: Fx = t*x*(2*x + 3*x*y + 2))/2
  • #131: Ft = t^2*(x + (3*x*y)/2 + 1/2) Fy = (t*y*(4*x + 3*x*y + 2))/2
  • #135: Warning: Explicit integral could not be found. ans =int(sin(x)*exp(-x^2),x)
  • #138: F_num_int = 0.4024 We can do it directly: syms x quad('sin(x).*exp(-x.^2)',0,pi/2)
  • #141: defint_sym =4*atan(4) + exp(4) - log(17)/2 – 1 defint_dbl = 57.4848
  • #142: defint_numint = 57.4848
  • #146: y =(x+5)*(x-3)*(x+2)
  • #148: f_col_x = 2*x*t+t f_col_t = (1+2*x)*t f_col = 2*x*t+t
  • #153: sol_c = -1/4*b^2-1/2*b
  • #155: ans = -3.2361 1.2361 ans = -3.2361 1.2361 *** Note that the results from both approaches are the same.