MatlabManual

advertisement
MATLAB
Matlab is all about matrices. Even adding 2+2 is adding two 1x1 matrices!
After starting, MATLAB we can type into the Command Window directly though generally it is
probably better to save commands into a script file and run that (see below).
Typing a command without a
semicolon will cause “echo” to
the screen.
To clear the Command
Window type clc.
MATLAB is
case sensitive.
After entering an expression or formula , the answer “ans” is given immediately
>> 2+2
ans =
4
D:\106748778.doc
1
Creating a Script File
Scripts are know as m-files eg test.m
o Click New.
o Enter code and
save it as test.m
o Run the script
by typing its
filename.
o The result of
running the script
appears.
o To edit, either double-click on the
file or use the Open button above.
D:\106748778.doc
Hint: Make your first command in the
script file clc to clear the screen each
time eg
clc
A=1
2
Matrices
Scalars, Vectors Matrices
In general MATLAB stores numeric data in matrices.
Vectors are stored in matrices with only one row or column, scalars are just 1-by-1 matrices.
2.1.1 Entering data
To enter a matrix explicitly, simply type in the Command Window
>> A = [1 2 3; 4 5 6; 7 8 9]
Typing a row: use a space or a comma
For a new column use a semicolon.
or
>> A = [1,2,3; 4,5,6; 7,8,9]
MATLAB displays the matrix you just entered:
A=
123
456
789
Once a matrix has been entered, it is automatically remembered in the MATLAB workspace. It
can be simply referred to by typing A.
D:\106748778.doc
3
Subscripts
The element in the row i and the column j of A is denoted by A(i,j).
eg typing
A = [1 2 3; 4 5 6; 7 8 9] and then
>> A(1,3) + A(3,2)
will give the result
Hint: To retrieve a previous
command use the up arrow
on the keyboard.
The retrieved line can be
edited as well!
ans =
11
If you assign a value to a position that is out of the range of the matrix, MATLAB increases the
size automatically!
>> X = A;
>> X(3,4) = 10
X=
1230
4560
7 8 9 10
2.1.3
D:\106748778.doc
4
Colon operator
The expression
>> 1:10 is a row vector containing the integers from 1 to 10: So just type 1:10 in the command
window.
ans =
1 2 3 4 5 6 7 8 9 10
or ans =
Columns 1 through 8
1 2 3 4 5 6
Columns 9 through 10
9 10
7
8
To specify an increment: Type:
>> 8:2:20
ans =
8 10 12
14
16
18
20
To obtain non-unit spacing, specify an increment:
>> 15:-2.5:5
ans =
15 12.5 10 7.5 5
Subscript expressions involving colons refer to portions of a matrix:
>> A(1:k,j)
is the first k elements of the jth column of A. The colon by itself refers to all the elements in a row
or column of a matrix and the keyword end refers to the last row or column.
>> A(:,end)
represents the last column vector of A:
ans =
3
6
9
4
D:\106748778.doc
5
Variables
MATLAB does not require any type declarations or dimension statements!
ie just type ! eg.
>> num_students = 25
creates a 1-by-1 matrix named num_students and stores the value 25 in its element.
Variable names consist of a letter, followed by any number of letters, digits, or underscores.
Numbers
MATLAB uses conventional decimal notation, with an optional decimal point and leading plus or
minus sign, for numbers.
3 -99 0.0001
9.6397238 1.60210e-20 6.02252e23
1i -3.14159j 3e5i
All numbers are stored internally using the long format specified by the IEEE floating-point
standard.
Floating-point numbers have a finite precision of roughly 16 significant decimal digits and a finite
range of roughly 10−308 to 10+308.
Operators
Expressions use familiar arithmetic operators and precedence rules.
+ Addition
- Subtraction
* Multiplication
/ Division
\ Left Division
^ Power
Built-In Functions
MATLAB provides a large number of standard elementary mathematical functions, including abs,
sqrt, exp, and sin. For a list of the elementary mathematical functions, type
>> help elfun
For a list of more advanced mathematical and matrix functions, type
>> help specfun
>> help elmat
D:\106748778.doc
6
MATLAB provides different functions that generate basic matrices.
zeros
ones
rand
randn
All zeros
(learn : important!)
All ones
(learn : important!)
Uniformly distributed random elements
Normally distributed random elements
Here are some examples:
>> Z = zeros(2,4)
ie 2 rows of 4 columns of 0’s
Z=
0000
0000
zeros(5,5) can be written as shorthand as zero(5). (beware!)
>> F = 5*ones(3,3)
F=
555
555
555
>> R = randn(4,4)
R=
0.6353 0.0860 -0.3210 -1.2316
-0.6014 -2.0046 1.2366 1.0556
0.5512 -0.4931 -0.6313 -0.1132
-1.0998 0.4620 -2.3252 0.3792
>> N = 10*rand(1,10)
0.3571 8.4913 9.3399
7.4313 3.9223 6.5548
>> N = fix(10*rand(1,10))
N=
9264874084
D:\106748778.doc
6.7874
1.7119
7.5774
7.0605
fix Rounds towards zero.
(Type help fix)
7
Concatenation
Concatenation is the process of joining small matrices to make bigger ones. The pair of square
brackets [] is the concatenation operator. For example:
>> v = [1;4;7];
v is a (column) vector in this case.
>> A = [v v+1 v+2]
v+1 means add 1 to every element in v,
A=
123
456
789
Deleting Rows And Columns
Complete rows and columns can be deleted by using just a pair of square brackets
>> X = A;
>> X(:,2) = []
ie column 2 is deleted.
A=
123
456
789
This changes X to
X=
13
46
79
Saving and Loading
The save function saves variables that exists in the MATLAB Workspace. For example,
typing the entries of a certain matrix:
>> A = [1 2 3; 4 5 6; 7 8 9]
To save this variable in a binary file, type
:
>> save matrix.mat A
(or any other name besides matrix.mat?)
The load function reads binary files containing matrices generated by earlier MATLAB
sessions, or reads text files containing numeric data.
For example loading a text file containing these four lines. The statement
>> load matrix.mat
(no mention of M!)
reads the file matrix.mat and creates a variable A containing the example matrix.
D:\106748778.doc
8
Linear Algebra
Matrix Operations
Multiplication The multiplication symbol * denotes matrix multiplication involving inner products
between rows and columns:
if A= [1 3] and B= [2 ; 4]
then
>> A*B
ans =
14
Transpose
The matrix transpose can be applied by using transpose or, for real matrices, by using ’.
eg >> B= [2 4]'
B=
2
4
is exactly the same as B= [2 ; 4]
Today’s useless information: Adding a matrix to its
transpose produces a symmetric matrix:
A = [1 2 3; 4 5 6; 7 8 9]
>> A + A’
ans =
2
6
6
10
10
14
10
14
18
Determinant The determinant of a matrix can be computed by det().
>> A=[1 2;3 4]
A=
1 2
3 4
>> det(A)
ans =
-2
D:\106748778.doc
9
Inverse The inverse can be obtained just by
>> inv(A)
eg if
>> A=[1 2;3 4] then
to format as rational numbers use
>> inv(A)
ans =
-2.0000 1.0000
1.5000 -0.5000
>> format rat
>> inv(A)
ans =
-2
1
3/2
-1/2
of course if we multiply a matrix by its inverse we get the identity matrix:
>> A*inv(A)
to restore formatting use
>> format
ans =
1.0000
0.0000
D:\106748778.doc
0
1.0000
10
Controlling Input and Output
Format Function
The format function controls the numeric format of the values displayed by MATLAB. The function
affects only how numbers are displayed, not how MATLAB computes or saves them.
Examples
>> x = [4/3 1.2345e-6]
>> format short
x=
1.3333 0.0000
>> format short e
x=
1.3333e+000 1.2345e-006
>> format short g
x=
1.3333 1.2345e-006
>> format long
x=
1.33333333333333 0.00000123450000
>> format rat
x=
4/3 1/810045
In addition
>> format compact
Suppresses many of the blank lines that appear in the output.
>> A = magic(100);
Entering Long Statements
If a statement does not fit on one line, use an ellipsis (three periods) ... followed by Return or
Enter to indicate that the statement continues on the next line. For example,
>> s = 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + 1/7 ...
- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;
Blank spaces around the =, +, and - signs are optional, but they improve readability.
D:\106748778.doc
11
Programming
Flow Control
if
The if statement evaluates a logical expression and executes a group of statements when the
expression is true.
The optional elseif and else keywords provide for the execution of alternate groups of statements.
An end keyword, which matches the if, terminates the last group of statements. The groups of
statements are delineated by the four keywords–no braces or brackets are involved.
if A > B
’greater’
elseif A < B
’less’
elseif A == B
’equal’
else
error(’Unexpected situation’)
end
switch and case
The switch statement executes groups of statements based on the value of a variable or
expression.
The keywords case and otherwise delineate the groups. Only the first matching case is executed.
There must always be an end to match the switch.
switch(value)
case 0
M=A
case 1
M=B
Otherwise
M=C
end
Unlike the C language switch statement, MATLAB switch does not fall through.
If the first case statement is true, the other case statements do not execute. So, break statements
are not required.
D:\106748778.doc
12
for
The for loop repeats a group of statements a fixed, predetermined number of times. A matching
end delineates the statements.
for i = 3 : 3 : 12
A(i) = 5;
end
The result will be a 1-by-12 vector with every third value equals 5.
Remark: The MATLAB for loop is very slow. Try to avoid it. eg
Instead of the example given above, use:
A(3:3:12) = 5
while
The while loop repeats a group of statements an indefinite number of times under control of a
logical condition. A matching end delineates the statements.
while A > B
A = A - 1;
end
continue
The continue statement passes control to the next iteration of the for or while loop in which it
appears, skipping any remaining statements in the body of the loop. In nested loops, continue
passes control to the next iteration of the for or while loop enclosing it.
break
The break statement lets you exit early from a for or while loop. In nested loops, break exits from
the innermost loop only.
D:\106748778.doc
13
m-flies
MATLAB is a powerful programming language as well as an interactive computational
environment. Files that contain code in the MATLAB language are called m-files. You create Mfiles using a text editor, then use them as you would any other MATLAB function or command.
Scripts and Functions
There are two kinds of M-files:
Scripts
When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can
operate on existing data in the workspace, or they can create new data on which to operate.
Although scripts do not return output arguments, any variables that they create remain in the
workspace, to be used in subsequent computations. In addition, scripts can produce graphical
output using functions like plot. Example script that generates 32 random values with randn and
displays the values as bar graphic.
r = zeros(1,32);
for n = 1:32
r(n) = randn;
end
r
bar(r)
If this code is saved in a file called barrandn.m, the script can be started by simply typing
barrandn in the command line.
Functions
Functions are M-files that can accept input arguments and return output arguments.
The name of the M-file and of the function should be the same.
Functions operate on variables within their own workspace, separate from the workspace you
access at the MATLAB command prompt.
Example function sumup with one parameter a that sums up the values from 1 to a.
File sumup.m:
function r = sumup(a)
% Function that sums up the values from 1 to a
sum = 0;
for i = 1:a
D:\106748778.doc
14
sum = sum + i;
end
r = sum;
Typed in the command line sumup(5) produces:
>> sumup(5)
ans =
15
Function Handles You can create a handle to any MATLAB function and then use that handle as
a means of referencing the function. A function handle is typically passed in an argument list to
other functions, which can then execute, or evaluate, the function using the handle.
To construct a function handle in MATLAB use the at sign, @, before the function name.
The following example creates a function handle for the sumup function and assigns it to the
variable fhandle.
>> fhandle = @sumup;
Evaluate a function handle using the MATLAB feval function. The function plot fhandle, shown
below, receives a function handle and data, and then performs an evaluation of the function
handle on that data using feval.
function x = plot_fhandle(fhandle,data)
dimension = prod(size(data));
r = data;
for i = 1:prod(size(data))
r(i) = feval(fhandle,data(i));
end
x=r
plot(data,r,’+’)
Typing in the MATLAB command line
>> v = [ 1 2 3 4 5 ];
>> plot_fhandle(@sumup,v)
computes the results of the function sumup for the values within v and plots them.
Function Functions A class of functions called function functions works with nonlinear functions of
a scalar variable. That is, one function works on another function. The function functions include
D:\106748778.doc
15
• Zero finding
• Optimization
• Quadrature
• Ordinary differential equations
MATLAB represents the nonlinear function by a function M-file. For example a simple nonlinear
function:
y = 1./((x-.3).^2 + .01) + 1./((x-.9).^2 + .04) - 6;
Evaluate this function at a set of points in the interval 0 _ x _ 1
>> x = 0:0.002:1;
>> y = humps(x);
Then plot the function with
>> plot(x,y)
The graph in Figure 1 shows that the function has a local minimum near x
= 0.6. The function fminsearch finds the minimizer, the value of x where the
function takes on this minimum. The first argument to fminsearch is a function
handle to the function being minimized and the second argument is a rough
guess at the location of the minimum.
>> p = fminsearch(@humps,.5)
p=
0.6370
To evaluate the function at the minimizer
>> humps(p)
ans =
11.2528
D:\106748778.doc
16
Plotting
MATLAB provides a variety of functions for displaying vector data as line plots,
as well as functions for annotating and printing these graphs.
Create Line Plots
The plot function has different forms depending on the input arguments. For
example, if y is a vector, plot(y) produces a linear graph of the elements of y
versus the index of the elements of y. If you specify two vectors as arguments,
plot(x,y) produces a graph of y versus x.
For example the developing of the intensities in a single row of our image can
be plotted
>> plot(I(100,:));
The graph shows the intensities varying along line 100. If we plot row 10 with
plot(I(10,:)) we get a constant graph representing the line we have manipulated
before.
The command
>> grid on;
shows an underlying grid within the figure.
Adding Plots to an Existing Graph
You can add plots to an existing graph using the hold command. When you
set hold to on, MATLAB does not remove the existing graph; it adds the new
data to the current graph, rescaling if the new data falls outside the range of
the previous axis limits.
>> plot(I(100,:));
>> hold on;
>> plot(I(10,:));
plots both graphs in one figure. The hold command can be turned off by
typing hold off.
Specifying Data Point Markers, Line Styles And Colors
There are a lot of possibilities to specify the plotted graphs. You can define the
colors and line styles. It is also possible to plot only markers at the data points.
Here are some examples, for more information please read the MATLAB help.
>> plot(I(100,:),’r+’);
18
plots a red ’+’ at each data point.
>> plot(I(100,1:20:end),’-rs’,’LineWidth’,2,...
’MarkerEdgeColor’,’k’,...
’MarkerFaceColor’,’g’,...
’MarkerSize’,10);}
plots a graph (Figure 2) of every 20th pixel of row 100 and marks each data
point with a green rectangle.
Figure 2: Plot of every 20th pixel of row 100 in Image I
D:\106748778.doc
17
Setting Axis Parameters
MATLAB selects axis limits based on the range of the plotted data. You can
specify the limits manually using the axis command. Call axis with the new
limits defined as a four-element vector.
axis([xmin,xmax,ymin,ymax])
By default, MATLAB displays graphs in a rectangular axes that has the same
aspect ratio as the figure window. This makes optimum use of space available
for plotting. MATLAB provides control over the aspect ratio with the axis
command.
The command
axis square
19
makes the x- and y-axes equal in length. The square axes has one data unit in
x to equal two data units in y. If you want the x- and y-data units to be equal,
use the command
axis equal
This produces an axes that is rectangular in shape, but has equal scaling along
each axis.
If you want the axes shape to conform to the plotted data, use the tight option
in conjunction with equal.
axis equal tight
4.2.5 3D Plots
The plot3 function displays a three-dimensional plot (Figure 3) of a set of data
points. Example
>> t = 0:pi/50:10*pi;
>> plot3(sin(t),cos(t),t)
>> grid on
>> axis square
D:\106748778.doc
18
Symbolic Math
Similar notation, with "D" denoting differentiation, is used for
% for ordinary differential equations by the "dsolve" function.
>> y = dsolve('Dy = -a*y')
y=
No need for syms!
C1*exp(-a*t)
pause % Strike any key to continue.
% Specify an initial condition.
>> y = dsolve('Dy = -a*y','y(0) = 1' )
y=
exp(-a*t)
pause will wait for keystroke.
Note that t is expected – not x.
>> y = dsolve('Dy = t')
y=
1/2*t^2+C1
% To produce symbolic output
Method 1 : Use syms: % You can either find the zeros of a symbolic expression, without quotes:
syms a b c x r
r=
(a*x^2 + b*x + c);
% Method 2: Use quotes:
r = solve( 'a*x^2 + b*x + c = 0' );
% Both of these produce the same result:
r=
1/2/a*(-b+(b^2-4*a*c)^(1/2))
1/2/a*(-b-(b^2-4*a*c)^(1/2))
% The solution could be returned in a structure:
S = solve('x^2 + x*y + y = 3', 'x^2 - 4*x + 3 = 0')
S=
x: [2x1 sym]
y: [2x1 sym]
S.x
ans =
1
3
D:\106748778.doc
19
S.y
ans =
1
-3/2
% The second derivative is denoted by "D2'.
y = dsolve('D2y = -a^2*y', 'y(0) = 1, Dy(pi/a) = 0')
y=
cos(a*t)
% It is sometimes desirable to use the simple or simplify function
% to transform expressions into more convenient forms.
f = cos(x)^2 + sin(x)^2
f=
cos(x)^2+sin(x)^2
f = simple(f)
f=
1
>> c= {1,'ed'}
c=
[1] 'ed'
>> c{1}
ans =
1
>> c(1)
ans =
[1]
>> c(2)
ans =
'ed'
>> x.i = 1
x=
i: 1
>> x.j = 2
x=
i: 1
j: 2
>> x
x=
i: 1
j: 2
D:\106748778.doc
20
>>
a=
0
0
0
0
3
0
0
0
0
4
0
0
0
0
0
0
>> A=sparse(a)
A=
(1,2)
3
(2,3)
4
>>
>> X=full(A)
X=
0 3 0
0 0 4
0 0 0
0 0 0
>>
0
0
0
0
>> f=@twoX
>> f(2)
twoX =
4
>>
Anonymous Functions
>> f=@(x)2*x
Same as before but it is
not given a name which
was two in that case.
>> f(3)
ans =
6
D:\106748778.doc
21
Using C:
Code for book
http://www.cise.ufl.edu/research/sparse/MATLAB/Files/ (ie the booklet? Or printed notes?)
#include "mex.h"
void mexFunction
(
int nargout,
mxArray *pargout [ ],
int nargin,
const mxArray *pargin [ ]
)
{
mexPrintf ("hello world\n") ;
}
>> mex –setup
Please choose your compiler for building external interface (MEX) files:
Would you like mex to locate installed compilers [y]/n? y
Select a compiler:
[1] Digital Visual Fortran version 6.0 in C:\Program Files\Microsoft Visual Studio
[2] Lcc C version 2.4 in C:\MATLAB7\sys\lcc
[3] Microsoft Visual C/C++ version 6.0 in C:\Program Files\Microsoft Visual Studio
[0] None
Write a c function
Compiler: 2
Please verify your choices:
Compiler: Lcc C 2.4
Location: C:\MATLAB7\sys\lcc
Are these correct?([y]/n): y
Try to update options file: C:\Documents and Settings\O(wner\Application
Data\MathWorks\MATLAB\R14\mexopts.bat
From template:
C:\MATLAB7\BIN\WIN32\mexopts\lccopts.bat
Done . . .
>> mex hello.c
>> hello
hello world
>> load handel
D:\106748778.doc
22
>> sound(y,Fs)
D:\106748778.doc
23
>>syms x
>> f = sym('f(x)')
f=
f(x)
>> g=sym('g(x)')
g=
g(x)
>> pretty(diff(f*g))
/d
\
/d
\
|-- f(x)| g(x) + f(x) |-- g(x)|
\dx /
\dx /
>> pretty(diff(f/g))
d
/d
\
-- f(x) f(x) |-- g(x)|
dx
\dx /
------- - -------------g(x)
2
g(x)
>> pretty(simple(diff(f^n)))
(n - 1) /d
\
f(x)
n |-- f(x)|
\dx /
>> syms x a b
>> f=x/(a*x+b)
f=
x/(a*x+b)
>> pretty(f)
x
------ax+b
>> g=int(f)
g=
1/a*x-b/a^2*log(a*x+b)
>> pretty(g)
b log(a x + b)
x/a - -------------2
a
D:\106748778.doc
24
>> latex(g)
ans =
{\frac {x}{a}}-{\frac {b\ln \left( ax+b \right) }{{a}^{2}}}
>> ccode(g)
ans =
t0 = 1/a*x-b/(a*a)*log(a*x+b);
>> fortran(g)
ans =
t0 = 1/a*x-b/a**2*log(a*x+b)
>> int(g)
ans =
1/2/a*x^2-b/a^2*log(a*x+b)*x-b^2/a^3*log(a*x+b)+b/a^2*x+b^2/a^3
>> pretty(ans)
2
2
2
x b log(a x + b) x b log(a x + b) b x b
1/2 ---- - ---------------- - --------------- + --- + ---a
2
3
2
3
a
a
a
a
Partial Differentation:
>> syms x y
>> g= x*y + x^2;
>> diff(g)
ans =
y+2*x
(Assumes wrt x)
>> diff(g,x)
ans =
y+2*x
(Same result but explicitly wrt x)
>> diff(g,y)
ans =
x
(x*y + x^2 wrt y)
page 129
>> syms x x1 x2 theta
>> F=x*(x1*x2 + x1 - 2);
>> findsym(F,1)
ans =
x
>> diff(F,x)
ans =
D:\106748778.doc
25
x1*x2+x1-2
>> diff(F,x1)
ans =
x*(x2+1)
>> diff(F,x2)
ans =
x*x1
>> G=cos(theta*x)
G=
cos(theta*x)
>> diff(G,theta)
ans =
-sin(theta*x)*x
>> syms h n x
>> limit((1+x/n)^n, n, inf)
ans =
exp(x)
limits
>> limit(sin(x)/x,x,0)
ans =
1
>> taylor(cos(x))
ans =
1-1/2*x^2+1/24*x^4
>> taylor(cos(x),8)
ans =
1-1/2*x^2+1/24*x^4-1/720*x^6
>> pretty(vpa('pi',100))
3.14159265358979323846264338327950288419716939937510582097494459230781640\
6286208998628034825342117068
>> syms x s t
>> subs(sin(x),x,pi/3)
ans =
0.8660
>> subs(sin(x),x,sym(pi)/3)
ans =
1/2*3^(1/2)
D:\106748778.doc
26
>> double(ans)
ans = 0.8660
>> subs(g*t^2/2, t, sqrt(2*s))
ans =(x*y+x^2)*s
>> subs(sqrt(1-x^2), x, cos(x))
ans =(1-cos(x)^2)^(1/2)
>> subs(sqrt(1-x^2), 1-x^2, cos(x))
ans =cos(x)^(1/2)
>> syms x
S = x^y
>> subs (S,x,3)
ans =3^y
>> subs(S,{x y},{3 2})
ans = 9
>> subs(S,{x y}, {3 x+1})
ans =3^(x+1)
>> syms a b x y z
expand((a + b)^5)
ans =a^5+5*a^4*b+10*a^3*b^2+10*a^2*b^3+5*a*b^4+b^5
factor(ans)
ans =(a+b)^5
collect(x * (x * (x + 3) + 5) + 1)
ans =1+x^3+3*x^2+5*x
horner(ans)
x*(x*(x+3)+5)+1
>> factor(sym('4248'))
ans =
(2)^3*(3)^2*(59)
D:\106748778.doc
27
syms t x y
ezplot(sin(2*x))
>> ezplot(x*exp(-x), [-1 4])
Page 138
x = t-sin(t)
y = 1-cos(t)
ezplot(x,y, [-4*pi 4*pi])
>> ezpolar(sin(3*t))
%16.7 Three-dimensional surface graphs
%16.8 Three-dimensional curves
>> x = 3*t / (1+t^3);
D:\106748778.doc
28
y = 3*t^2 / (1+t^3);
z = sin(t);
ezplot3(x,y,z)
>> ezplot3(x,y,z,'animate')
%16.9 Symbolic matrix operations
a = magic(3)
A = sym(a)
a=
8 1
3 5
4 9
A=
[ 8, 1, 6]
[ 3, 5, 7]
[ 4, 9, 2]
6
7
2
>> syms a b s
K = [a + b, a - b ; b - a, a + b]
K=
[ a+b, a-b]
[ b-a, a+b]
D:\106748778.doc
29
>> G = [cos(s), sin(s); -sin(s), cos(s)]
G=
[ cos(s), sin(s)]
[ -sin(s), cos(s)]
>> sqr = inline(´x^2´)
>> sqr(3)
>> figure(4)
>> hold on Get ready to plot, but don’t quit plotting until you’re told to.
>> ezplot(´sin(x)´, [-pi,pi]) Graph f(x) = sin x over the interval [−π, π].
>> ezplot(´sin(2*x)´, [-pi,pi]) Graph f(x) = sin 2x over the interval [−π, π].
syms t;
>> ezplot3(t^2*sin(10*t), t^2*cos(10*t), t,'animate');
plot plots matrices
x = -2.9:0.2:2.9;
bar(x,exp(-x.*x),'r')
f = @(x)2*x;
fplot(f, [-1 1])
syms x
z1= 2*x
z2=3*x
z=z1+z2
>> z=z1+z2
z=
5*x
ezplot(z)
syms x
syms('pi')
n=1
f = 8/((2*n-1) * pi)*(-1)^(n+1)*cos((2*n-1)*x);
ezplot(f)
D:\106748778.doc
30
http://mathcs.holycross.edu/~spl/MATLAB/matlab.html
The command who returns a list of all variables in the current workspace, while whos
returns the same list with more detailed information about each variable.
>> who
Your variables are:
ans
x
y
>> whos
Name
ans
x
y
Size
Bytes
1x1
1x1
1x1
8
8
8
Class
double array
double array
double array
The function dot computes the dot product of two vectors in Rn .
>> v=[7; 23; 15; 2], w=[5; -2; 1; -8]
v =
7
23
15
2
w =
5
-2
1
-8
>> dot(v,w)
ans =
-1
The length of a vector can also be found directly using the norm function.
>> norm(v)
ans =
28.4077
The function cross computes the cross product of two vectors in R3.
>> v=[3; 2; 1], w=[4; 15; 1]
v =
3
2
1
w =
4
15
D:\106748778.doc
31
1
>> x=cross(v,w)
x =
-13
1
37
The * in scalar multiplication is not optional.
>> 2A
??? 2
|
Missing operator, comma, or semi-colon.
The rref command is used to compute the reduced row echelon form of a matrix.
>> A=[1 2 3 4 5 6; 1 2 4 8 16 32;
A =
1
2
3
4
5
1
2
4
8
16
2
4
2
4
2
1
2
1
2
1
>> rref(A)
ans =
1
2
0
0
-4
0
0
1
0
-1
0
0
0
1
3
2 4 2 4 2 4; 1 2 1 2 1 2]
6
32
4
2
-8
-6
8
The rank of a matrix equals the dimension of its column space
>> A=[1 2 1 4; 2 3 1 3; 3 2 1 2; 4 3 1 1]
A =
1
2
1
4
2
3
1
3
3
2
1
2
4
3
1
1
>> rank(A)
ans =
3
If we just wanted to find the eigenvectors from scratch, we would use the null command.
>> A=[3 1 1; 1 3 1; 1 1 3]
A =
3
1
1
1
3
1
1
1
3
>> C1 = null(A-2*eye(3),'r')
C1 =
eye(3) is a 3x3 identity matrix.
(2 is one Eigen values)
Eigen values are 5, 2, 2.
D:\106748778.doc
Eigen vectors are
[ 1, -1, -1]
[ 1, 1, 0]
[ 1, 0, 1]
32
-1
1
0
-1
0
1
>> C2 = null(A-5*eye(3),'r')
C2 =
1
1
1
Systems of equations can also be handled by solve.
>> S = solve('x+y+z=1','x+2*y-z=3')
S =
x: [1x1 sym]
y: [1x1 sym]
The variable S contains the solution, which consists of x and y in terms of z.
>> S.x
ans =
-3*z-1
>> S.y
ans =
2*z+2
Animation
% curve.m
% Shows animation of a parametric curve being plotted.
hold on
for T=0:.1:4*pi
t=[T T+.1];
plot(2*t.*cos(t)./(t+1),2*t.*sin(t)./(t+1))
axis equal
axis([-2 2 -2 2])
axis off
pause(.01)
end
D:\106748778.doc
33
Fourier
syms x
syms('pi')
n=1
f1 = 8/((2*n-1) * pi)*(-1)^(n+1)*cos((2*n-1)*x)
ezplot(f1, [-4 4])
Save this code as Fourier.m
Repeat for n=2. (Modify the Fourier file above and run it again.)
Now plot both curves together:
syms x
syms('pi')
hold on
n=2
f2 = 8/((2*n-1) * pi)*(-1)^(n+1)*cos((2*n-1)*x)
ezplot(f2, [-4 4])
n=1
f1 = 8/((2*n-1) * pi)*(-1)^(n+1)*cos((2*n-1)*x)
ezplot(f1, [-4 4])
D:\106748778.doc
34
Now plot the SUM as well – by adding this code to the file above.
f = f1 + f2
h=ezplot(f, [-4 4])
set(h, 'Color', 'm');
You may need to close this ‘figure’
before running the program again
lest more graphs are ADDED if you
run the since the hold is on.
Exactly the same effect can be achieved as above using a loop:
syms x
syms('pi')
hold on
f=0
for n = 1:2
c = 8/((2*n-1) * pi)*(-1)^(n+1)*cos((2*n-1)*x)
ezplot(c, [-4 4])
f=f+c
end
h = ezplot(f, [-4 4]);
set(h, 'Color', 'm');
D:\106748778.doc
35
But..
clc will clear the command window.
Increase n say 10, 20 etc
You may wish to switch off the blue graphs: comment out
%ezplot(c, [-4 4])
Fourier’s theorem says that any periodic wave in this case a periodic square wave can be
synthesized by a sum of sin or cos functions.
You may wish to increase the time interval to demonstrate this periodicity:
h = ezplot(f, [-10 10]);
See page 186 Old Edition Stroud Advanced for the Fourier series formulas
..and page 188 for the method of evaluating the coefficients a n for the example above.
D:\106748778.doc
36
Page 333 Stroud Advanced, Numerical DE solution.
When using FFT algorithms, a distinction is made between the window length and the transform
length. The window length is the length of the input data vector. It is determined by, for example,
the size of an external buffer. The transform length is the length of the output, the computed DFT.
An FFT algorithm pads or chops the input to achieve the desired transform length. The following
figure illustrates the two lengths.
The execution time of an FFT algorithm depends on the transform length. It is fastest when the
transform length is a power of two, and almost as fast when the transform length has only small
prime factors. It is typically slower for transform lengths that are prime or have large prime
factors. Time differences, however, are reduced to insignificance by modern FFT algorithms such
as those used in MATLAB. Adjusting the transform length for efficiency is usually unnecessary in
practice
D:\106748778.doc
37
x=[0,.1,.5,.4,1.2];
dftx=fft(x)
Output:
dftx =
Columns 1 through 4 :
2.2000
-0.3264 + 0.9874i -0.7736 + 0.7417i -0.7736 - 0.7417i
Column 5 :
-0.3264 - 0.9874i
clc;
x = [0 .1 .5 .4 1.2]
y=0;
for J = 1:5
y=y+exp(-2*pi/5*(J-1)*i)* x(J)
end
syms w a
f = exp(-w^2/(4*a^2));
F = ifourier(f)
F = simple(F)
syms t
f = sin(t)+sin(2*t);
F = fourier(f)
Output:
F = i*pi*(-dirac(w-1)+dirac(w+2)-dirac(w-2)+dirac(w+1))
****************************************************
f= ifourier(F)
Output:
f=
sin(x)*(2*cos(x)+1)
D:\106748778.doc
38
page 14 of notes
syms t a real
a=2;
f = exp (-a * abs(t) );
F = fourier(f)
Output:
F = 4/(4+w^2)
syms t
f = dirac(t);
F = fourier(f)
Output:
F=1
syms a real;
f = exp(-w^2/(4*a^2));
F = ifourier(f);
F = simple(F)
Output:
F = ifourier(exp(-1/4*w^2/a^2),w,x)
D:\106748778.doc
39
%see matlab reference for fft
Saved as FFT.m
t = 0:0.001:0.6; % 600 samples!
x = sin(2*pi*50*t)+ sin(2*pi*120*t);
y = x + 2*randn(size(t));
%plot(1000*t(1:50),y(1:50)) % first 50 y values and same for t except
these are x 1000 ie 1 to 50
title('Signal Corrupted with Zero-Mean Random Noise')
xlabel('time (milliseconds)')
Y = fft(y,512); % take 512 samples (there are only 50 input data values
originally! (A power of 2 is apparently an optimum value for the FFT
algorithm.)
%The power spectrum, a measurement of the power at various frequencies,
is
Pyy = Y.* conj(Y) / 512; %Formula for the power. Note we need something
REAL to plot it! (Could also take the abs() as well?
%Graph the first 257 points (the other 255 points are redundant) on a
meaningful frequency axis:
f = 1000*(0:511)/512;
plot(f,Pyy(1:512))
title('Frequency content of y')
xlabel('frequency (Hz)')
D:\106748778.doc
40
Now cut down the output:
f = 1000*(0:256)/512;
plot(f,Pyy(1:257))
DFT Discreet Fourier Transform
clc;
x=[0, 0.1, 0.5, 0.4];
dftx=fft(x)
(N = 4)
dftx = 1.0000 + 0.0000i -0.5000 + 0.3000i 0.0000 + 0.0000i -0.5000 - 0.3000i
D:\106748778.doc
41
see matlab reference for filter
http://www.mathworks.co.uk/help/matlab/ref/filter.html
You can use filter to find a running average without using a for loop. This example finds
the running average of a 16-element vector, using a window size of 5
data = [1:0.2:4]'
windowSize = 5;
filter(ones(1,windowSize)/windowSize,1,data);
.20
.44
etc
*******************************************
clc
syms t
a=2;
%must a have a VALUE?
f = heaviside(t)* exp(-a*t) ;
F = fourier(f)
% F=simple(F)
F = 1/(2+i*w)
ones(1,windowSize)/windowSize=
0.2000 0.2000 0.2000 0.2000
0.2000
clc
syms t real
f = cos(3*t)+ 2* cos(5*t);
F = fourier(f)
F = pi*(2*dirac(w+5)+2*dirac(w-5)+dirac(w-3)+dirac(w+3))
***************************************************************************
D:\106748778.doc
42
Plotting 3D Mesh
x = 0:.5:1;
[X,Y] = meshgrid(x,x);
Note the dot – otherwise it will
multiply the 2 matrices
together – not piecewise.
Z = X.* Y
mesh(x,x,Z);
axis([0 1 0 1 0 2])
xlabel('X');
ylabel('Y');
zlabel('Z');
X
0
0
0
0.5
0.5
0.5
1
1
1
Y
0
0.5
1
0
0.5
1
0
0.5
1
Z
0
0
0
0
0.25
0.5
0
0.5
1
D:\106748778.doc
43
x = 0:.01:1;
[X,Y] = meshgrid(x,x);
Page 20 M2 notes
Z=0;
for n = 1:2:1
K = -4/(pi*n*sinh(n*pi));
Z = Z + K * sinh(n * pi*(X-1)).* sin(n* pi*Y) ;
end
mesh(x,x,Z);
xlabel('X');
ylabel('Y');
zlabel('Z');
D:\106748778.doc
n=1
n=3
n=5
n = 101
44
D:\106748778.doc
45
Lagrange Polar Plot
Page 32 M2
Jack’s
clear all
[t,r] = meshgrid(linspace(0,pi,181),linspace(0,1,181));
figure('color','white');
P=0;
for n=1:2:1
K=4/pi/n^2;
P=P+K*(r.^n).*sin(n*t);
end
polarplot3d(P,'plottype','surfcn','angularrange', [0 pi]);
n=1
n = 101
D:\106748778.doc
46
Wave equation
x = 0:.01:1;
[X,T] = meshgrid(x,x);
N = 101;
c=1;
Z=0;
for n = 1:2:N
a = 4/(pi^2)*sin(n*pi/2)/(n^2);
Z = Z + a * sin(n * pi*(X)).* cos(n*pi*c*T) ;
end
Wave.m
Page 46 lecture
o/heads.
mesh(x,x,Z);
xlabel('X');
ylabel('Y');
zlabel('Z');
Use n = 1 inc velocity c= 4
D:\106748778.doc
47
Plotting
>> x = -1:.1: 1;
>> y = x.^3
>> plot(y)
Variance Using a Matlab Function
function varn = variance(d1,d2,d3)
m = (d1 + d2 + d3)/3;
.
MUST save this as a
separate file.
MUST be named
variance.m
varn = ((d1-m)^2 + (d2-m)^2 + (d3-m)^2)/3.0;
% sqrt to get sd
See variance.m
No endfunction ??
To run it:
>> s= variance(1,2,3)
Result:
s=
0.6667
D:\106748778.doc
48
>> polar(t,1-sin(t))
Note the difference using syms or not:
>> syms r
>> diff (r^2)
ans =
2*r
If we don’t use syms:
>> clear r
>> diff (r^2)
??? Undefined function or variable 'r'.
>> x=2;
>> x + x
ans =
4
>> syms x
>> x+x
ans =
2*x
D:\106748778.doc
49
Solving Equations
A=
0
-2
1
-3
0x + y = 2
-2x – 3y = -8
>> B= [2 ;-8]
for AX=B
>> inv(A) * B
ans =
1
2
But easier and quicker is:
>> x= A\B
x=
1
2
Note the \ - not /.
Not B\A !
We have solved =ns of the form Ax=B for X
Solution -> x= A\B.
What if we wished to solve an equation of the form xA=B?
Solution -> x= A/B.
eg
clc;
>> x= [1;2]
x=
1
2
A= [3
1
B= [2
1
2;
2];
2;
3];
>> A = [3 4]
A= 3 4
C=A*B;
>> B = x * A
% AB = C
B=
3
6
Arep = C *inv(B);% ie A or C/B ie C by inverse of B
Brep = inv(A)*C; % ie B or A\C ie inverse of A times C
4
8
>> x = B/A
x=
1
2
Arep = C/B
Brep = A\C
Arep =
3
1
2
2
2
Brep =
2
1
D:\106748778.doc
2
3
50
Simulink
See Matlab Help:Building a Model
o New Model.
Model ...
o Sine
Wave.
o Sources.
D:\106748778.doc
51
Drag arrows as shown and then …
o Hold down the
control key and
then drag.
D:\106748778.doc
52
o Double-click to
open Scope
window.
D:\106748778.doc
53
Eigen Values/Vectors
Eigen Values/Vectors are used to solve simultaneous equations. (Later)
A = [ 0 1
-2 -3];
Try this:
[V,D] = eig(A)
Result
V=
0.7071 -0.4472
-0.7071 0.8944
0.7071
--0.7071
and
are the eigen vectors. Eigen vectors are not unique. It
is really just the ratios y:x that we are interested in so
for example these below are equivalent to these
respective eigen vectors.
1
-1
D=
-1
0
0
-2
-0.4472
0.8944
1
-2
-1 and -2 are the
(corresponding)
eigen values.
So we have:
V=
[1
-1
-1 ;
-2];
and
D=
-1
0
0
-2
Eigen values and eigen vectors are defined such
that AX = λX where X is an eigen vector and λ is a
corresponding eigen value. Show that this is true in
both cases for our matrix A.
Here’s the first one done for you:
A = [ 0 1 ;-2 -3];
lambda1 = -1;
X= [ 1
-1] ;
A*X -> ?
lambda1*X -> ?
D:\106748778.doc
54
Diagonalization
A diagonal matrix is one with numbers only along the leading diagonal the rest being zeros
like so
[ -1 0]
[ 0 -2]
let V be the matrix of corresponding eigen vectors.
If we premultiply a matrix by V and post multiply by inv(V) then the result is a diagonal matrix of
the eigen vectors.
page 47 o/heads
clc;
clear all;
format
A = [ 0
1;
-2 -3]
[V D] = eig(A)
V * A * inv(V);
A=
0
-2
1
-3
V=
0.7071 -0.4472
-0.7071 0.8944
D=
-1
0
0
-2
D:\106748778.doc
55
Diagonalization
A diagonal matrix is one with numbers only along the leading diagonal the rest being zeros
like so [ 2 0]
[ 0 3]
BUT rather confusingly diagonalization does not mean finding such a single matrix
It means:
V * A * V-1
-> D
In Matlab P-1 is inv(P).
where
V consists of the eigen vectors of A.
D will then be a diagonal matrix with the (corresponding) eigen values along its diagonal.
eg
A = [ 0 1
-2 -3];
V=
1
-1
1
-2
V is the matrix whose columns are
the eigen vectors of A.
0
-2
.. and D is the result - a diagonal
matrix whose diagonal is the eigen
values of A.
D=
-1
0
In Matlab->
A = [ 0 1;-2 -3];
V = [1 -1 ; -1 -2];
ie
1 -1
-1 -2
V * A * inv(V)
=
0 1
-2 -3
Result:
0 1
-2 -3
easier:
A = [ 0
1;
-2 -3]
[V D] = eig(A)
V * A * inv(V)
A=
0 1
-2 -3
V=
0.7071 -0.4472
-0.7071 0.8944
D=
-1
0
0
-2
-1 0
0 -2
x
x
x
x
Note AV=VD
V * D
A * V
ans =
-0.7071 0.8944
0.7071 -1.7889
ans =
-0.7071 0.8944
0.7071 -1.7889
ie same.
D:\106748778.doc
56
Diagonalization
continued.
Ref: wiki diagonalizable matrix
For
A=
0
-2
What if we wanted to find A10?
1
-3
It so happens that when we multiply these out we get a purely diagonal
matrix D whose leading diagonal contains the eigen values of A.
We had the eigen vectors:
Now A10 => ?
E1 =
1
-2
A10 = (P D P-1)10 = P D10 P-1
So A10 = P D10 P-1
E2 =
1
-1
Where can D^10 easily be found using D.^10
1. Make a matrix whose columns are the eigen vectors
>> V = [E1 E2]
V=
1
-1
1
-2
2. Then
>> A = inv(V) * D * V
D=
-2
0
0
-1
note V A V-1 -> D
ie the eigen values
across the leading
diagonal.
A^2 =
(V doesn’t need to be
normalized.)
Must be in this order:
inv(V) * D * V
A diagonal matrix
results whose diagonal
is the eigen values!
0 1
-2 -3
0 1
-2
-2 -3 = 6
-3
7
Corresponding to
the eigen vectors.
Note also that
A=V * D * inv(V)
D:\106748778.doc
57
syms v d
[v,d] = eig(A)
>> eigen
A=
[ 0, 1]
[ -2, -3]
v=
[ 1, -1]
[ -2, 1]
Eigen vectors.
d=
[ -2, 0]
[ 0, -1]
Eigen values are -1 & -2
SVD
[U,D,V] = svd(A)
U=
-0.2298
0.9732
0.9732
0.2298
D=
V is also a matrix of
eigen vectors but
normalized.
U is the inverse of V
and D is the
diagonal vector - of
eigen values.
3.7025
0
0 0.5402
V=
-0.5257 -0.8507
-0.8507 0.5257
>> U * D * V
ans =
-0.00 1.00
-2.00 -3.00
ie A :
0 1
-2 -3
D:\106748778.doc
58
A^2 is also just
V * D.^2 * inv(V)
Note that
One of these sandwich
matrices is the matrix of
A’s eigen vectors and the
other is the inverse of this.
>> D^2
ans =
1
0
0
4
1 1
-1 -2
o Just square
the elements!
1
0
0
4
2 1
-1 -1
-1 4
-1 8
2 1
-1 -1
-2 -3
6 7
So To Raise A to the Power of 10
eg A^10 is just
P * D.^10 * inv(P)
If
D=
-1
0
0
-2
If D is a diagonal matrix then
eg D^10 is easily obtained by
raising to the tenth power the
elements individually on the
leading diagonal.
>> D.^10
ans =
1
0
0
1024
Recall that
P=
1
-1
So A^10
1
-2
P * D.^10 * inv(P)
>>
A = [ 0 1;-2 -3];
P = [1 1 ; -1 -2];
D = [1 0 ; 0 1024]
ans =
-1022
2046
-1023
2047
A10 = P * D * inv(P)
>>
Compare this with Matlab’s brute force:
>> A^10
ans =
-1022
-1023
2046
2047
D:\106748778.doc
For 3x3 example see
http://en.wikipedia.org/wiki/
Diagonalizable_matrix
Or page 494 Stroud Advanced.
59
rand()
Example 1.
R = rand(3,4)
may produce R =
0.2190
0.0470
0.6789
0.6793
0.9347
0.3835
0.5194
0.8310
0.0346
0.0535
0.5297
0.6711
Eigenvalue Decomposition To compute the Eigenvalues and the Eigenvectors
>> [V,D] = eig(A)
Singular Value Decomposition To compute the Singular Value Decomposition
of a matrix A
>> [U,D,V] = svd(A)
D:\106748778.doc
60
Polynomials
x^2-3x-2=0
p = [1 -3 2];
r = roots(p)
r=
2
1
p = poly(r)
p=
1
-3
2
The polyval function evaluates a polynomial at a specified value.
To evaluate p at s = 5, use polyval(p,5)
ans =
See Polynomials in Mathematics in MATLAB in Help
110
Straight Line Fit
X= [1 2 3];
Y= [2 3 1];
p = polyfit(X,Y,1);
Y2 = polyval(p,X);
plot(X,Y,'o',X,Y2)
grid on
D:\106748778.doc
61
The poly function also computes the coefficients of the characteristic polynomial of a matrix.
Apply this to our eigen matrix
A = [ 0 1;-2 -3]
>> p= poly(A)
p=
1
3
x^2 – 3x +2 = 0
2
>> roots(p)
ans =
If using sym we
get the actual
polynomial eg
x^2 +.. etc.
(Eigen values.)
-2
-1
Multiplication and Division Of Polynomials.
multiplication and division correspond to the operations convolution and deconvolution.
The functions conv and deconv implement these operations.
Consider the polynomials x^2 +2x+3 and 4x^2 +5x + 6.
To compute their product, a = [1 2 3]; b = [4 5 6];
c = conv(a,b)
c=
4
13
28
27
18
-> 4x^4 +13x^3 + 28x^2 + 27x + 18
Use deconvolution to divide back out of the product. [q,r] = deconv(c,a)
q=
4
5
6
r=
0
0
0
D:\106748778.doc
-> 4x^2 +5x + 6
0
0
-> no remainder
62
Polynomial Curve Fitting (already done?)
polyfit finds the coefficients of a polynomial that fits a set of data in a least-squares sense.
p = polyfit(x,y,n)
x and y are vectors containing the x and y data to be fitted, and n is the order of the polynomial to
return.
For example, consider the x-y test data. x = [1 2 3 4 5]; y = [5.5 43.1 128 290.7 498.4];
A third order polynomial that approximately fits the data is p = polyfit(x,y,3)
p = -0.1917 31.5821 -60.3262 35.3400
x = [1 2 3 4 5]; y = [5.5 43.1 128 290.7 498.4];
p = polyfit(x,y,3)
x1 = 1:.1:5
y1 =p(1)*x1.^3 +p(2)*x1.^2 + p(3)*x1 +p(4)
plot(x,y,'o',x1,y1)
D:\106748778.doc
63
Partial Fraction Expansion
residue finds the partial fraction expansion of the ratio of two polynomials. This is particularly
useful for applications that represent systems in transfer function form. For polynomials b and a, if
there are no multiple roots, where r is a column vector of residues, p is a column vector of pole
locations, and k is a row vector of direct terms. Consider the transfer function
b = [-4 8];
a = [1 6 8];
[r,p,k] = residue(b,a)
r=
-12
8
p=
-4
-2
k=
[]
Given three input arguments (r, p, and k), residue converts back to polynomial form. [b2,a2] =
residue(r,p,k)
b2 =
-4
a2 =
1
8
6
D:\106748778.doc
8
64
Cell Arrays
A Cell Array can be an array of arrays eg
Search cell arrays in help
A Cell Array can therefore contain
different data types.
C = {'one', 'two', 'three'; 1, 2, 3};
Access the data elements using indexed braces:
C{1,1}
clc;
b=ones(2,2)
1
1
1
1
A = magic(2)
1
3
4
2
Note the difference: eg
[A b]gives one concatenated array
1
3
1
1
4
2
1
1
whereas:
C={A, b}; is an array of arrays.
-> ‘one’
and being an array we must use two indices
in this case
Parentheses are used to access sets of cells eg
C(:,1:2)
-> 'one'
[ 1]
columns 1 to 2 inclusive.
The whole row of such columns.
'two'
[ 2]
X=C{1,1} gives the whole (first)array:
X =
1
4
3
2
X(2,2)->2
or C{1,1}(2,2) -> 2
It seems we can also use parentheses to access one element?
>> C(1,1)
-> ‘one’
after using C(:,1:2)??
If the data in the cell array is numeric:
D = {4, 5, 6;
1, 2, 3};
Then we can convert it to an ‘ordinary’ array:
cell2num or something
->
E =
4
5
6
1
2
3
D:\106748778.doc
65
Create an empty array with the cell function, such as
A = cell(3,4);
Creates an array of matrices.
A{1,1} = [1 2]
->
A=
[1x2 double]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
and…
an array!
o We can also enter data by double-clicking on a cell here and…
…a separate cell editor opens up for that cell.
o Enter some numbers.
D:\106748778.doc
66
M = cell(8,1);
An 8 x 1 array ie 8 rows of matrices.
for n = 1:8
M{n} = magic(n);
End
M
>> M{1}, M{2}, M{3}
M=
->
[
1]
[2x2 double]
[3x3 double]
[4x4 double]
[5x5 double]
[6x6 double]
[7x7 double]
[8x8 double]
ans =
1
ans =
1
4
3
2
ans =
8
3
4
1
5
9
6
7
2
etc.
D:\106748778.doc
67
Interpolation
Polynomial Regression
Based on the plot, it is possible that the data can be modelled by a polynomial function The
unknown coefficients a0, a1, and a2 can be computed by doing a least squares fit, which
minimizes the sum of the squares of the deviations of the data from the model. There are six
equations in three unknowns, represented by the 6-by-3 matrix X = [ones(size(t)) t t.^2]
X=
1.0000
0
0
1.0000 0.3000 0.0900
1.0000 0.8000 0.6400
1.0000 1.1000 1.2100
1.0000 1.6000 2.5600
1.0000 2.3000 5.2900
The solution is found with the backslash operator. a = X\y
a=
0.5318
0.9191
- 0.2387
The second-order polynomial model of the data is therefore Now evaluate the model at regularly
spaced points and overlay the original data in a plot. T = (0:0.1:2.5)';
Y = [ones(size(T)) T T.^2]*a;
plot(T,Y,'-',t,y,'o'), grid on
Clearly this fit does not perfectly approximate t
D:\106748778.doc
68
DE’s
http://en.wikibooks.org/wiki/MATLAB_Programming/Ordinary_Differential_Equations
All of the differential equations have the same syntax that you must use, and the same
input and output arguments. All of the solvers require three input arguments: a function
handle to the differential equation you want to solve, a time interval over which to
integrate, and a set of initial conditions. Let us suppose we want to solve the simple
differential equation y' = y, y(0) = 1, which has the true solution y(t) = e^t. Suppose we
want the solution between t = 0 and t = 1.
To use function handles, you must first create an M-file with the function in it like so:
function Yprime = func(t, y)
Yprime = 0;
Yprime = y;
dy/dx = y
… and call it thus: ode45(@func, [0,1], 1)
As per usual the name of the m-file and
of the function should be the same.
func.m
interval is [0,1]and when t= 0 y = 1.
The result: (ie a graph for free)
We have used @ to define a function
handle which can then be used/called
from the function as shown.
(Or we could explicitly define the function
handle first eg f = @func and then call it
like so:
ode45(f, [0,1], 1)
might need to clear all first here.)
dy/dt = y. -> y = e^t
On the other hand if we use:
[t,y]=ode45(@func, [0,1], 1) we just get the matrices t and y which is the solution.
t=
0
0.0250
0.0500
0.0750
...
0.9750
1.0000
y=
1.0000
1.0253
1.0513
…
2.6512
2.7183
D:\106748778.doc
69
3-D Plot
Plot commands such as plot and meshgrid as distinct from
symbolic plot function such as ezplot act upon a series of
matrix data – usually x & y. In this case we need the elementwise dot operator eg X.^2
x = -1.5:.04:1.5;
y = -1.5:.04:1.5;
[X,Y] = meshgrid(x,y);
Z = X.^2+ Y.^2 + Y -1;
mesh(X,Y,Z)
xlabel('X');
ylabel('Y');
zlabel('Z');
Z=X.^3- X.^2 - Y.^2 + 8
;
saddle.m
D:\106748778.doc
70
cat
Given
A = [ 1
3
2 ;
4 ]
B = [ 5
7
6 ;
8 ]
concatenating along different dimensions produces
down
across
back
C=cat(3,A,B)
C(1,1,2) -> 5
ie 3nd dimension 1st element
mind you:
>> [A B]
ans =
1 2
3 4
5
7
6
8
>> [A; B]
ans =
1 2
3 4
5 6
7 8
D:\106748778.doc
71
Cell Array
cell arrays can contain arrays as elements
cell arrays are indexed to return the “composite” element in this case
an array at that position
eg if
C = {[1],
[2 3 4];
[5; 9], [6 7 8; 10 11 12]};
C =
1
5
9
2
6
10
3
7
11
4
8
12
The arrays don’t have to “fit”….
then
C{2,1}
produces the array at position (1,1)
ans =
5
9
but we can convert all to numbers:
A = cell2mat(C)
A =
1
2
3
4
5
6
7
8
9
10
11
12
then obviously eg A(2,1)
->
…but the arrays must “fit” to use cell2mat.
5.
Cell Array can also be used for variable length strings
http://uk.mathworks.com/help/matlab/matlab_prog/cell-arrays-of-strings.html
clc;
clear all;
A = {'ed' 'marge'}
A{1}
A{1}(1)
A =
'ed'
'marge'
ans =
ed
ans =
e
D:\106748778.doc
72
http://uk.mathworks.com/help/matlab/matlab_prog/formatting-strings.html
mvec = [77 65 84 76 65 66];
sprintf('%s ', char(mvec))
A = pi*100*ones(1,5);
sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)
http://uk.mathworks.com/help/matlab/ref/strcmp.html
s1 = 'Yes';
s2 = 'No';
tf = strcmp(s1,s2)
http://uk.mathworks.com/help/matlab/ref/strtrim.html
S = strtrim(str)
C = strtrim(cstr)
>> version
ans =
8.1.0.604 (R2013a)
available in Matlab R2014b
clc;
clear all;
% datetime('06301994')
% d = [20140628 20140701 20140704]
% t = datetime(d,'ConvertFrom','yyyymmdd')
% % d = yyyymmdd(t)
% DateStrings = {'2014-05-26';'2014-08-03'};
% t = datetime(DateStrings,'InputFormat','yyyy-MM-dd');
% t = datetime('now','TimeZone','local','Format','d-MMM-y HH:mm:ss Z')
Y = [2014;2013;2012];
M = 01;
D = [31;30;31];
t = datetime(Y,M,D)
D:\106748778.doc
73
The meaning of the : (colon) operator.
: means “every element” .
eg
A =
A=
1
3
[1 2 ;3
4]
2
4
A( : , 2) %means every element in column 2.
ans =
2
4
A( 2 , : ) %means row 2 every element.
ans =
3 4
Variance
clc;
clear all
format rat
A=[1 2 3]
var(A,1)
ans =
2/3
(divides by n)
var(A,0)
ans =
1
(divides by n-1)
D:\106748778.doc
74
clc;
clear all
syms q
A=[q 1-q 0;
0 q 1-q;
0 0 q ]
A^2
ans =
[ q^2, -2*q*(q - 1), (q - 1)^2]
[ 0,
q^2, -2*q*(q - 1)]
[ 0,
0,
q^2]
-----------------------------clc;
clear all
q = .6
A=[q 1-q 0;
0 q 1-q;
0 0 q ]
A^2 * [31 0 0]'
ans =
11.1600
0
0
For example
fprintf('Call Price at t=0 is %4.5f', V1(1))
The % means it’s is a “placeholder” for the value that’s after the comma.
f means print a decimal.
4.5'means print 4 numbers max to the left of the dec place (I think!) and 5 dec places to the
right.
ie 3.74779
%
….. s means string etc.
D:\106748778.doc
75
clear all;
format compact
syms k1 k2 k3 s ;
n=3;
I = eye(n);
k1=1;
A0= [-3
0
-2*k1
1
-2
-2*k2
0 ;
1
-2*k3-4]
D=s*I -A0
dt=det(D)
C=collect(dt,s)
coeffs(C,s)
A0 =
[ -3, 1,
0]
[ 0, -2,
1]
[ -2, -2*k2, - 2*k3 - 4]
D=
[ s + 3, -1,
0]
[ 0, s + 2,
-1]
[ 2, 2*k2, 2*k3 + s + 4]
dt =
6*k2 + 12*k3 + 26*s + 2*k2*s + 10*k3*s + 2*k3*s^2 + 9*s^2 + s^3 + 26
C=
s^3 + (2*k3 + 9)*s^2 + (2*k2 + 10*k3 + 26)*s + 6*k2 + 12*k3 + 26
ans =
[ 6*k2 + 12*k3 + 26, 2*k2 + 10*k3 + 26, 2*k3 + 9, 1]
>>
D:\106748778.doc
76
swap 2 columns
clc;
A = magic(4)
A(:,[1 3]) = A(:,[3 1])
ingenious!
D:\106748778.doc
77
Download