Download An Introductory Lecture MATLAB, which stands for

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Trigonometric functions wikipedia , lookup

Transcript
www.mcdtu.wordpress.com
An Introductory Lecture
MATLAB, which stands for MATrixLABoratory, is a state-of-the-art
mathematical software package, which is used extensively in both
academia and industry. It is an interactive program for numerical
computation and data visualization, which along with its programming
capabilities provides a very useful tool for almost all areas of science
and engineering.
MATLAB® is a high-level language and interactive environment that
enablesyou to perform computationally intensive tasks faster than with
traditionalprogramming languages such as C, C++, and Fortran.
Key Features
• High-level language for technical computing
• Development environment for managing code, files, and data
• Interactive tools for iterative exploration, design, and problem solving
• Mathematical functions for linear algebra, statistics, Fourier analysis,
filtering, optimization, and numerical integration
• 2-D and 3-D graphics functions for visualizing data
• Tools for building custom graphical user interfaces
• Functions for integrating MATLAB based algorithms with external
applications and languages, such as C, C++, Fortran, Java etc.
www.mcdtu.wordpress.com 1
www.mcdtu.wordpress.com
Desktop
When you start MATLAB, the desktop appears in its default layout.
www.mcdtu.wordpress.com 2
www.mcdtu.wordpress.com
The desktop includes these panels:
• Current Folder — Access your files.
• Command Window — Enter commands at the command line, indicated
by the prompt (>>).
• Workspace — Explore data that you create or import from files.
• Command History — View or rerun commands that you entered at the
command line.
There are two more windows which are hidden:
 Figure window
 Editor window
Built-in functions
There are numerous built-in functions (i.e. commands) in MATLAB. We will
mention a few of them in this section by separating them into categories.
Scalar Functions
Certain MATLAB functions are essentially used on scalars, but operate elementwise when applied to a matrix (or vector). They are summarized in the table
below.
sin
cos
tan
asin
acos
trigonometric sine
trigonometric cosine
trigonometric tangent
trigonometric inverse sine (arcsine)
trigonometric inverse cosine (arccosine)
www.mcdtu.wordpress.com 3
www.mcdtu.wordpress.com
atan
trigonometric inverse tangent (arctangent)
exp
exponential
log
natural logarithm
abs
absolute value
sqrt
square root
rem
remainder
round round towards nearest integer
floor
round towards negative infinity
ceil
round towards positive infinity
Note: It is strongly recommended to get help on all of them to find out exactly
how they are used.The trigonometric functions take as input radians.
Vector Functions
Other MATLAB functions operate essentially on vectors returning a scalar value.
Some of these functions are given in the table below.
max
largest component
min
smallest component
length
length of a vector
sort
sort in ascending order
sum
sum of elements
prod
product of elements
median
median value
mean mean value
std
standard deviation
Matrix Functions
Much of MATLAB‘s power comes from its matrix functions. These can be further
separated into two sub-categories. The first one consists of convenient matrix
building functions, some of which are given in the table below.
eye
zeros
ones
identity matrix
matrix of zeros
matrix of ones
www.mcdtu.wordpress.com 4
www.mcdtu.wordpress.com
diag
triu
tril
rand
extract diagonal of a matrix or create diagonal matrices
upper triangular part of a matrix
lower triangular part of a matrix
randomly generated matrix
Let us now summarize some of the commands in the second sub-category of
matrix functions.
size
det
inv
rank
rref
eig
poly
norm
cond
lu
qr
chol
svd
size of a matrix
determinant of a square matrix
inverse of a matrix
rank of a matrix
reduced row echelon form
eigenvalues and eigenvectors
characteristic polynomial
norm of matrix (1-norm, 2-norm, ∞ -norm)
condition number in the 2-norm
LU factorization
QR factorization
Cholesky decomposition
singular value decomposition
Symbols and meaning
+
Addition, - subtraction, * Multiplication, / Division, ^ Exponentiation
Start Working
>>3 + 4
ans =
7
π = 3.1415…
www.mcdtu.wordpress.com 5
www.mcdtu.wordpress.com
>>sin(pi/2)
ans =
1
% use this symbol to write comments
>> a=2
% stores a=2
a =
2
>> b=3
% stores b=3
b =
3
>>a+b
% calculates the sum
ans =
5
NOTE: Use clear command to erase the value stored in a and b.
Array Creation
To create an array with four elements in a single row, separate the elements
with either a comma (,)oraspace.
>>clear
>> a=[1, 2,3,4]
a =
1
2
3
4
To create a matrix that has multiple rows, separate the
rows with semicolons.
www.mcdtu.wordpress.com 6
www.mcdtu.wordpress.com
>>
b=[1 2 3; 3 4 6; 6 4 1]
b =
1
3
6
2
4
4
3
6
1
Matrix and Array Operations
>>b^2
%square
ans =
25
51
24
22
46
32
18
39
43
The command whos gives all sorts of information on what variables are active.
A similar command, called who, only provides the names of the variables that are
active.
>>whos
Name
a
ans
b
Size
Bytes
1x4
3x3
3x3
32
72
72
Class
Attributes
double
double
double
To create a vector whose entries are 0, 1, 2, 3, …, 7, 8, you can type
>> c=[0:8]
c =
0
1
2
3
4
5
6
7
www.mcdtu.wordpress.com 7
8
www.mcdtu.wordpress.com
To obtain a vector whose entries are 0, 2, 4, 6, and 8, you can type in the following
line:
>> d=[0:2:8]
d =
0
2
4
6
8
This work can be done using the command linspace as follows:
>> r=linspace(0,8,5)
r =
0
2
4
6
8
Solving Linear system of equations: ax=b
>>clear
>> a=[1 1 1; 2 5 7; 2 1 -1]
a =
1
2
2
1
5
1
1
7
-1
>> b=[9;52;0]
b =
9
52
0
>> a\b
www.mcdtu.wordpress.com 8
www.mcdtu.wordpress.com
ans =
1
3
5
Note: The table below summarizes the operators that are available in MATLAB.
'
\
/
transpose
left division
right division
Element by element operation:
.*
.^
./
.\
multiplication
Exponentiation
Right division
\left division
>>clear
>> a=[1 2 3; 0 3 4; 2 3 2]
a =
1
0
2
2
3
3
3
4
2
>> b=[1 2 3; 0 3 4; 2 3 2]
b =
1
0
2
2
3
3
3
4
2
>> a.*b
www.mcdtu.wordpress.com 9
www.mcdtu.wordpress.com
ans =
1
0
4
4
9
9
9
16
4
Using COLON (:) in addressing arrays:
a(:,n) elements in all the rows of column n of the matrix a
>>a(:,2)
ans =
2
3
3
a(n,:) elements in all the columns of row n of the matrix a
>>a(2,:)
ans =
0
3
4
Plotting
Oneof the most important and basic features of MATLAB is the commands for
data visualization (i.e. plotting. For two-dimensional plotting):
The PLOT command: The plot command has the following syntax
plot(x,y,’linespecifier’, ‘property_name’,’property_value )
x, y: are vectors
Line_specifiers : defines and specify the type and color of the line and markers
www.mcdtu.wordpress.com 10
www.mcdtu.wordpress.com
Property name and value: are optional can be use to define the color and width of
line and marker.
A marker is a symbol thatappears at each plotted data point, such as a +, o,or *. For
example, 'g:*'requests a dotted green line with * markers.
If x and y are two vectors of the same length then plot(x,y) plots x versus y.
>>clear
>> x=[-pi:.1:pi];
>> y=cos(x);
>>plot(x,y)
% x and y are vectors
>>xlabel('x')
>>ylabel('cos x')
>>title('graph of cos x between -pi to pi')
To add plots to an existing figure, use hold.
>> y=cos(x);
>>plot(x,y)
>>xlabel('x')
>>ylabel('sin x')
>> x = 0:pi/100:2*pi;
>>y = sin(x);
www.mcdtu.wordpress.com 11
www.mcdtu.wordpress.com
>>plot(x,y)
>>hold on
>>y2 = cos(x);
>>plot(x,y2,'r:')
>>legend('sin','cos')
% The legend function provides an easy way to identify
the individual lines:
The fplotcommand :
It has the following syntax
fplot(‘function’, ‘limits’, line_specifiers)
1. The function can be typed directly, eg. 4*t*sin(t)+t^2-2 etc.
www.mcdtu.wordpress.com 12
www.mcdtu.wordpress.com
2. Limits specifies the domain of x as [xmin, xmax] or
[xmin, xmax, ymin,ymax]
>> hold off
>>clear
>>fplot('4*t*sin(t)+t^2-2',[-pi, pi])
Plotting multiple graphs in one figure:
>> clear all
>> x=[-2:0.1:4];
>> y=3*x.^3-26*x+6;
>>yd=9*x.^2-26;
>>ydd=18*x;
>>plot(x,y,'-b',x,yd,'--r', x,ydd,':k')
www.mcdtu.wordpress.com 13
www.mcdtu.wordpress.com
>>legend('y', 'yd', 'ydd')
www.mcdtu.wordpress.com 14
www.mcdtu.wordpress.com
Working with Anonymous functions:
An Anonymous function is a function of ne or more variables that we create on the
command line for subsequent evaluations. Such a function can be used several
times in programming or where ever needed.
Syntax:
fun_name=@(list of input variables separated by comma)
fun_expression
>>clear
>> f=@(x,y) x*y^2-3*y+4*x^4
f =
@(x,y)x*y^2-3*y+4*x^4
>>f(0,1)
ans =
-3
>>f(0 1)
www.mcdtu.wordpress.com 15
www.mcdtu.wordpress.com
The problem is that with the Matlab that the commands in the command window
can‘t be saved and executed again. In, addition to that the command window is not
interactive. A different way of executing commands with Matlab is first to create
a file with a list of commands, save it, and then run the file. I f the change is
required it can be made easily. Such files are called ―m-files‖ because they must
have the filename extension ―.m‖. This extension is required in order for these
files to be interpreted by MATLAB.
There are two types of m-files: script files and function files.
Script files contain a sequence of usual MATLAB commands, that are executed
(in order) once the script is called within MATLAB. For example, if such a file
has the name compute.m , then typing the command compute at the MATLAB
prompt will cause the statements in that file to be executed. Script files can be
very useful when entering data into a matrix.
Ex.
game(1)=input('points scored in game 1');
game(2)=input('points scored in game 2');
game(3)=input('points scored in game 3');
game=[game(1) game(2) game(3)];
ave_points=mean(game);
fprintf('an average of %f points was
scored in three games',ave_points)
%save this file with name avrg.m, by typing name of the file in the command
window:
>> clear all
>>avrg
points scored
points scored
points scored
an average of
in game 1
in game 2
in game 3
48.000000
54
34
56
points was scored in three games
Function files, on the other hand, play the role of user defined commands that
often have input and output. A user defined function is a matlab program that is
created by the user, saved as a function file, and then can be used like build-in
function.
www.mcdtu.wordpress.com 16
www.mcdtu.wordpress.com
Input data (1hr)
Function file
Output data(60mins)
Structure of a function file:
The first executable line in a function file must be the function definition line.
Otherwise it will considered as a script file. I t has the following format:
function[output arguments]= fun_name (input arguments)
EX.
function y = value(x) % function definition
y=(x.^4.*sqrt(3*x+5))./(x.^2+1).^2;
%save this file with the name value.m as function file.
>>value(6) % type the command and the value of x
ans =
4.5401
% If x is a vector then
>> x=1:2:11
x =
1
3
>>value(x)
ans =
0.7071
6.0638
5
7
3.0307
9
11
4.1347
4.8971
5.5197
Inline function: In the case when value of a function is to be determined
many times within program, inline function is used. I has the following
syntax
name= inline(‘math_expression typed as a string’)
www.mcdtu.wordpress.com 17
www.mcdtu.wordpress.com
Ex.
>> y=inline('(x.^4.*sqrt(3*x+5))./(x.^2+1).^2')
% one variable
y =
Inline function:
y(x) = (x.^4.*sqrt(3*x+5))./(x.^2+1).^2
>>y(6)
ans =
4.5401
For several variable it has the following form:
name= inline(‘math_expression
‘arg1’, ‘arg2’, ‘arg3’)
typed
as
a
string’,
>> z=inline('2*x^2-4*x*y+y^2','x','y')
% x , y shows the order arguments
z =
Inline function:
z(x,y) = 2*x^2-4*x*y+y^2
>>z(2,3)
ans =
-7
The feval command:This command evaluates the value of the function
for a given value/s of the functions arguments. I t has the following
syntax:
Variable=feval(‗function_name‘, argument_value)
www.mcdtu.wordpress.com 18
www.mcdtu.wordpress.com
Ex.
>>feval('sqrt',84)
ans =
9.1652
>>value=feval('sqrt',64)
value =
8
Note: This command is useful in the situations when the value of the
function has to be calculated inside another function. For example builtin function fzero finds the zero of a function with one variable.
www.mcdtu.wordpress.com 19
www.mcdtu.wordpress.com
PROGRAMMING IN MATLAB
Operators:
1. Relational operators: <, >, <=, >=, ==, =, ~=
If two scalars are compared then result is either 0 or 1. In arrays comparison is
done element by element in two arrays of the same order.
>> 2>0
ans =
1
>> 3<-0
ans =
0
2. Relational operators: &, |, ~
There are built-in logical functions in matlab that are equivalent to the logical
operators:
and(A,B) same as A&B
or(A,B) same as A|B
not(A,B) same as ~A
Conditional Statements:
The conditional statement is a command that allows Matlab to make a decision.
The basic form of the a conditional statement is:
If
conditional expression
www.mcdtu.wordpress.com 20
www.mcdtu.wordpress.com
Ex. if a<=b; if a==b ; x~=2
1. The if-end structure
if conditional_exp
group of commands
end
Ex. Calculate workers pay
t=input('Input the number of hrs worked');
h=input('Hourly wages in Rs');
pay= t*h;
if t>40
pay=pay+(t-40)*0.5*h;
end
fprintf('The workers pay is Rs%5.2f',pay )
% save the file with name wrkpay and execute it
>>wrkpay
Input the number of hrs worked 19
Hourly wages in Rs 10 % no output
>>wrkpay
Input the number of hrs worked 50
Hourly wages in Rs 40
The workers pay is Rs2200.00
2. The if-else-end structure
if
conditional_exp
group of commands
else
group of commands
end
www.mcdtu.wordpress.com 21
www.mcdtu.wordpress.com
t=input('Input the number of hrs worked');
h=input('Hourly wages in Rs');
if t>40
pay=t*h+(t-40)*0.5*h;
else
pay=t*h;
fprintf('The workers pay is Rs%5.2f',pay )
end
fprintf('The workers pay is Rs%5.2f',pay )
1. The if-elseif-else-end structure
if
conditional_exp1
elseif
group of commands1
conditional exp2
group of commands2
else
group of commands3
end
t=input('Input the number of hrs worked');
h=input('Hourly wages in Rs');
if t>40
pay=t*h+(t-40)*0.5*h;
elseif (t<=40)&&(t>=20)
pay=t*h;
fprintf('The workers pay is Rs%5.2f',pay )
else
pay=t*(h-5);
fprintf('The workers pay is Rs%5.2f',pay )
end
fprintf('The workers pay is Rs%5.2f',pay )
www.mcdtu.wordpress.com 22
www.mcdtu.wordpress.com
>> wrkpay3
Input the number of hrs worked 15
Hourly wages in Rs 10
The workers pay is Rs75.00The workers pay is Rs75.00
>> wrkpay3
Input the number of hrs worked 20
Hourly wages in Rs 10
The workers pay is Rs200.00The workers pay is Rs200.00
>> wrkpay3
Input the number of hrs worked 19
Hourly wages in Rs 5
The workers pay is Rs 0.00The workers pay is Rs 0.00>>
clear
The switch-case statement is another method that can be used to affect the flow of
a program. It provides a means for choosing one group of commands for execution
out of several possible groups.
Switch among several cases based on expression
Syntax
switchswitch_expression
casecase_expression
statements
casecase_expression
statements
:
otherwise
statements
end
The switch expression can be scalar or a string.
Why Do We Need Numerical Methods?
www.mcdtu.wordpress.com 23
www.mcdtu.wordpress.com
Mathematics is an elegant and precise subject: however when numerical answers
are required one sometimes needs to rely on approximate methods to obtain
useable answers. There are many problems which simply do not have analytical
solutions, or those whose exact solution is beyond our current state of knowledge.
There are also many problems which are too long (or tedious) to solve by hand.
When such problems arise we can exploit numerical analysis to reduce the problem
to one involving a finite number of unknowns and use a computer to solve the
resulting equations.
>>syms x
>> y=diff(x^3)
>> y=diff(x^3)
y =
3*x^2
>> w=int(ans) % Used to integrate ans
Thus a simple command is enough for differentiation and integration tasks. As
mentioned above, MATLAB can perform symbolic calculus on expressions.
Consider the following
example:
syms x
f=sin(x^2)
f=
sin(x^2)
Can differentiate this expression using the diff command:
diff(f,x)
ans =
2*x*cos(x^2)
The same techniques work with expressions involving two or more variables:
syms x y
www.mcdtu.wordpress.com 24
www.mcdtu.wordpress.com
q=x^2*y^3*exp(x)
q =
x^2*y^3*exp(x)
pretty(q)
2 3
x yexp(x)
diff(q,y)
ans =
3*x^2*y^2*exp(x)
Thus MATLAB can compute partial derivatives just as easily as ordinary
derivatives.
One use of these capabilities to test whether a certain function is a solution of a
given differential equation.
For example, suppose wewant to check whether the function u(t)=e^at is a
solution of the ODE
𝑑𝑢
= 𝑎𝑢.
𝑑𝑡
Define
syms a t
u=exp(a*t)
u=
exp(a*t)
One can then compute the left side of the differential equation, and see if it agrees
with the right side (zero):
diff(u,t)-a*u
ans =
0
Thus the given function u is a solution. Is the function v(t)=at another solution?
We can check it as follows:
>>v=a*t
a*t
www.mcdtu.wordpress.com 25
www.mcdtu.wordpress.com
diff(v,t)-a*v
ans =
a - a^2*t
Since the result is not zero, the function v is not a solution.
It is no more difficult to check whether a function of several variables is the
solution of a PDE. For example, is w(x,y)=sin(πx)+sin(πy) a solution
of the differential equation
syms x y
w=sin(pi*x)+sin(pi*y)
w =
sin(pi*x) + sin(pi*y)
diff(w,x,2)+diff(w,y,2)
ans =
- pi^2*sin(pi*x) - pi^2*sin(pi*y)
simplify(ans)
ans =
-pi^2*(sin(pi*x) + sin(pi*y))
Since the result is not zero, the function w is not a
solution of the PDE.
The above example shows how to compute higher
derivatives of an expression. For example, here is the
fifth derivative of w with respect to x:
diff(w,x,5)
ans =
pi^5*cos(pi*x)
To compute a mixed partial derivative, we have to
iterate the diff command. Here is the mixed partial
derivative of w(x,y)=x^2*exp(y)+x*y^2 with respect to x
and then y:
www.mcdtu.wordpress.com 26
www.mcdtu.wordpress.com
syms x y
w=x^2*exp(y)+x*y^2
w =
x^2*exp(y) + x*y^2
diff(diff(w,x),y)
ans =
2*y + 2*x*exp(y)
Instead of using expressions in the above calculations,
we can use functions. Consider the following:
clear
syms a x
f=@(x)exp(a*x)
f =
@(x)exp(a*x)
diff(f(x),x)-a*f(x)
ans =
0
When defining a function that depends on a parameter
(like the function f above, which depends on a), the
value of the parametered is "captured" at the time when
the function is defined.
www.mcdtu.wordpress.com 27
www.mcdtu.wordpress.com
In mathematics, in the field of differential equations, a boundary value
problem is a differential equation together with a set of additional restraints, called
the boundary conditions. A solution to a boundary value problem is a solution to
the differential equation which also satisfies the boundary conditions.
Boundary value problems are similar to initial value problems. A boundary value
problem has conditions specified at the extremes ("boundaries") of the independent
variable in the equation whereas an initial value problem has all of the conditions
specified at the same value of the independent variable (and that value is at the
lower boundary of the domain, thus the term "initial" value). Finding the
temperature at all points of an iron bar with one end kept at absolute zero and the
other end at the freezing point of water would be a boundary value problem.
For example, if the independent variable is time over the domain [0,1], a boundary
value problem would specify values for
at both
and
, whereas an
initial value problem would specify a value of
and
at time
.
Boundary value problems arise in several branches of physics as any physical
differential equation will have them. Problems involving the wave equation, such
as the determination of normal modes, are often stated as boundary value
problems. A large class of important boundary value problems are theSturm–
Liouville problems. The analysis of these problems involves the eigenfunctions of
a differential operator.
To be useful in applications, a boundary value problem should be well posed. This
means that given the input to the problem there exists a unique solution, which
depends continuously on the input. Much theoretical work in the field of partial
differential equations is devoted to proving that boundary value problems arising
from scientific and engineering applications are in fact well-posed.
Among the earliest boundary value problems to be studied is the Dirichlet problem,
of finding the harmonic functions (solutions to Laplace's equation); the solution
was given by the Dirichlet's principle.
EXAMPLE 1: Solve:
𝑑𝑥
𝑑𝑡
=𝑥+𝑡
With 𝑥 0 = 0.
1. Write first order differential equation
www.mcdtu.wordpress.com 28
www.mcdtu.wordpress.com
𝑥 =𝑥+𝑡
2.
To compute the new derivative: and save this file with name
simpode.m.
function xdot = simpode(t,x);
% Computes xdot= x+t
% call syntax : xdot= simpode(t,x)
xdot= x+t;
3. Type the following codes in
the command window:
>> tspan = [0,2]; % specify time span
>> x0= 0;
% specify x0
>> [t,x]=ode23('simpode', tspan,x0);
>> plot(t,x)
% execute ode23
% plots graph
>> ylabel('x')
>> xlabel('t')
4. The
following graph will be appear
The symbolic solution is obtained by:
www.mcdtu.wordpress.com 29
www.mcdtu.wordpress.com
>> clear
>> x=dsolve('Dx=x+t','x(0)=0')
x =
exp(t) - t – 1
% The graph of this function is:
The second order differential equation can be solved in the following
way:
EX: 𝑦 ′′ = cos 2 𝑡 − 𝑦, 𝑦 0 = 0, 𝑦 ′ 0 = 0.
Sol:
>> clear
>> y=dsolve('D2y=cos(2*t)-y','y(0)=1','Dy(0)=0')
www.mcdtu.wordpress.com 30
www.mcdtu.wordpress.com
y =(5*cos(t))/3 + sin(t)*(sin(3*t)/6 + sin(t)/2)
- (2*cos(t)*(- 3*tan(t/2)^4 + 6*tan(t/2)^2 +
1))/(3*(tan(t/2)^2 + 1)^3)
% use simplify(y) command to simplify the output
>> simplify(y)
ans =
1 - (8*(cos(t)/2 - 1/2)^2)/3
>> ezplot(ans, [0,2])
% plot the graph of solution.
Higher Order Ordinary differential equation:
1.
ODE of order >=2, write the differential equation as a set of first order
ODEs. Basically we need to form the equation in the vector form
𝑥 = 𝑓(𝑥, 𝑡), where
www.mcdtu.wordpress.com 31
www.mcdtu.wordpress.com
x=[x1,x2,x3,…,xn]’.
2.
We need to write a function to compute the state derivatives
3.
Use the built-in ODEs solvers ode23 or ode45 to solve the set of
equations: It has the following syntax
[time, solution]=ode(‘your_function’,
tspan, x0)
% time: time vector
% solution matrix
% ode: in-built ode solver
% your_function: user written function with
the title line xdot =(your_function(t,x);)
this function contains the ODEs you want to
solve.
% tspan: time span [t0, t_final]
% x0: in initial condition
2. Second order non-linear ODE
Solve the equation of motion of a non linear pendulum.
𝜃 + 𝑤 2 sin 𝜃 = 0 𝑤𝑖𝑡ℎ𝑡ℎ𝑒𝑖𝑛𝑖𝑡𝑖𝑎𝑙𝑐𝑜𝑛𝑑𝑖𝑡𝑖𝑜𝑛𝑠𝜃 0 = 1, 𝜃 0 = 0.
1. Writing the equation into two first order differential equations.
Let 𝑧1 = 𝜃𝑎𝑛𝑑𝑧2 = 𝜃 then
𝑧1 = 𝜃 =𝑧2 and 𝑧2 = 𝜃 =-𝑤 2 sin 𝑧1
2. Write a function to compute new state derivative:
function zdot = pend(t,z);
% call syntax: zdot= pend (t,z);
% inputs: t=time
www.mcdtu.wordpress.com 32
www.mcdtu.wordpress.com
% z=[z(1); z(2)]= [theta; thetadot]
% output: zdot= [z(2); -w^2* sin z(1)]
wsq=1.56;
% specify the value of W^2
zdot= [z(2); -wsq*sin(z(1))]
Note that z(1) and z(2) refer to the first and second elements of the
vector z. Save this file with the name pend.m in the current folder.
3. Use ode23 or ode45 for solution.
>> tspan=[0 20]; z0=[1;0]; % the range of tsapn
indicates that equation is solved in that interval
% assign values to tspan, z0
>> [t,z]=ode23('pend', tspan, z0);
%running ode23
>> x=z(:,1); y=z(:,2); % x= column 1 of z, y= column 2
>> plot(t,x,t,y)
% plot t vs x and t vs y
>> xlabel('t');
% adding axis labels
>> ylabel('x and y');
>> figure(2)
% open a new figure window
>> plot (x,y)
%plot phase portrait
>> xlabel('Displacement'),ylabel('velocity')
%axes labels
>> title('phase plane plot')% title of the figure
www.mcdtu.wordpress.com 33
www.mcdtu.wordpress.com
Phase plane plot
www.mcdtu.wordpress.com 34
www.mcdtu.wordpress.com
Concretely, an example of a boundary value (in one spatial dimension) is the problem
to be solved for the unknown function
with the boundary conditions
Without the boundary conditions, the general solution to this equation is
From the boundary condition
which implies that
and so
one obtains
From the boundary condition
one finds
One sees that imposing boundary conditions allowed one to
determine a unique solution, which in this case is
www.mcdtu.wordpress.com 35