Documente Academic
Documente Profesional
Documente Cultură
MATLAB
Tutorial
Programming Language
Collection of Toolboxes
Command Window
Command History
Help Browser
Workspace Browser
Editor/Debugger
MATLAB Desktop Tools
MATLAB as Programming Language
High-level language
Data types
Functions
Control flow statements
Input/output
Graphics
Object-oriented programming capabilities
Toolboxes
Search Engine
Printable Documents
“Matlabroot\help\pdf_doc\”
Link to The MathWorks
Handling
Matrices in
Matlab
Matrices
Entering and Generating Matrices
Subscripts
Scalar Expansion
Concatenation
Deleting Rows and Columns
Array Extraction
Matrix and Array Multiplication
Note:
The resulting matrix must be rectangular
Array Subscripting / Indexing
1 2 3 4 5
A= 4
1
10
6
1
11
6
16
2
21
1
2
2 8 1.2 7 9 12 4 17
25 22
A(1:5,5) A(1:end,end)
3 7.2 3 5 8
7 13 1 18
11 23 A(:,5) A(:,end)
A(21:25) A(21:end)’
A(3,1) 4 0 4
0.5 9 4 14 5 19
56 24
A(3) 5 10 15 20 25
5 23 83 13 0 10
A(4:5,2:3)
A([9 14;10 15])
Deleting Rows and Columns
»» A=[1
A=[1 55 9;4
9;4 33 2.5;
2.5; 0.1
0.1 10
10 3i+1]
3i+1]
AA ==
1.0000
1.0000 5.0000
5.0000 9.0000
9.0000
4.0000
4.0000 3.0000
3.0000 2.5000
2.5000
0.1000
0.1000 10.0000
10.0000 1.0000+3.0000i
1.0000+3.0000i
»» A(:,2)=[]
A(:,2)=[]
AA == “:” is a VERY important construct in MATLAB
1.0000
1.0000 9.0000
9.0000
4.0000
4.0000 2.5000
2.5000
0.1000
0.1000 1.0000
1.0000 ++ 3.0000i
3.0000i
»» A(2,2)=[]
A(2,2)=[]
???
??? Indexed
Indexed empty
empty matrix
matrix assignment
assignment is
is not
not allowed.
allowed.
Matrix Multiplication
»» aa == [1
[1 22 33 4;
4; 55 66 77 8];
8]; [2x4]
»» bb == ones(4,3);
ones(4,3); [4x3]
»» cc == a*b
a*b [2x4]*[4x3] [2x3]
cc ==
10
10 10
10 10
10
26
26 26
26 26
26 a(2nd row).b(3rd column)
Logical Operators
Math Functions
= = equal to »» Mass
Mass == [-2
[-2 10
10 NaN
NaN 30
30 -11
-11 Inf
Inf 31];
31];
»» each_pos
each_pos == Mass>=0
Mass>=0
> greater than
each_pos
each_pos ==
< less than 00 11 00 11 00 11 11
»» all_pos
all_pos == all(Mass>=0)
all(Mass>=0)
>= Greater or equal all_pos
all_pos ==
<= less or equal 00
»» all_pos
all_pos == any(Mass>=0)
any(Mass>=0)
~ not all_pos
all_pos ==
11
& and
»» pos_fin
pos_fin == (Mass>=0)&(isfinite(Mass))
(Mass>=0)&(isfinite(Mass))
| or pos_fin
pos_fin ==
00 11 00 11 00 00 11
isfinite(), etc. . . .
all(), any() Note:
• 1 = TRUE
find
• 0 = FALSE
Elementary Math Function
Interpolation
One-Dimensional (interp1)
Two-Dimensional (interp2)
Example
polysam=[1
polysam=[1 00 00 8];
8];
roots(polysam)
roots(polysam)
ans
ans ==
-2.0000
-2.0000
1.0000
1.0000 ++ 1.7321i
1.7321i
1.0000
1.0000 -- 1.7321i
1.7321i
polyval(polysam,[0
polyval(polysam,[0 11 2.5
2.5 44 6.5])
6.5])
ans
ans ==
8.0000
8.0000 9.0000
9.0000 23.6250
23.6250 72.0000
72.0000 282.6250
282.6250
polyder(polysam)
polyder(polysam)
ans
ans ==
33 00 00
[r
[r pp k]=residue(polysam,[1
k]=residue(polysam,[1 44 3])
3])
rr == 9.59.5 3.5
3.5
pp == -3
-3 -1
-1
kk == 11 -4
-4
Curve fitting
polyfit(X,Y,N) - finds the
coefficients of a polynomial
P(X) of degree N that over the
points X fits the data Y best in
a least-squares sense
xx == [0:
[0: 0.1:
0.1: 2.5];
2.5];
yy == erf(x);
erf(x);
pp == polyfit(x,y,6)
polyfit(x,y,6)
pp ==
0.0084
0.0084 -0.0983
-0.0983 0.4217
0.4217 -0.7435
-0.7435 0.1471
0.1471 1.1064
1.1064 0.0004
0.0004
interp1(x,y,[0.45
interp1(x,y,[0.45 0.95
0.95 2.2
2.2 3.0])
3.0])
ans =
ans =
0.4744
0.4744 0.8198
0.8198 0.9981
0.9981 NaN
NaN
Exercise 2 (10 minutes)
Let x be an array of values from 0 to 2, equally
spaced by 0.01
Compute the array of exponentials corresponding to
the values stored in x
Find the polynomial p of degree 5 that is the best
least square approximation to y on the given interval
[0,2]
Evaluate the polynomial p at the values of x, and
compute the error z with respect to the array y
Interpolate the (x,z) data to approximate the value of
the error in interpolation at the point .9995
END
MATLAB for [Linear] Algebra
Programming
and
Application
Development
Topics discussed…
The concept of m-file in MATLAB
Variables in MATLAB
Type of a variable
Scope of a variable
The Editor/Debugger
Before Getting Lost in Details…
function
function [mean,stdev]
[mean,stdev] == ourstat(x)
ourstat(x)
[m,n]
[m,n] == size(x);
size(x);
Multiple Output
if
if mm ==
== 11
Arguments, use [ ]
m = n;
»[m std]=ourstat(1:9); endm = n;
end
mean
mean == sum(x)/m;
sum(x)/m;
stdev
stdev == sqrt(sum(x.^2)/m
sqrt(sum(x.^2)/m –– mean.^2);
mean.^2);
Basic Parts of a Function M-File
Output Arguments Function Name Input Arguments
• Function Files
• Let you make your own MATLAB Functions
• All variables within a function are local
• All information must be passed to functions as
parameters
• Subfunctions are supported
The concept of Workspace
• At any time in a MATLAB session, the code has a workspace
associated with it
• The workspace is like a sandbox in which you find yourself at a
certain point of executing MATLAB
• The “Base Workspace”: the workspace in which you live when
you execute commands from prompt
• Remarks:
• Each MATLAB function has its own workspace (its own
sandbox)
• A function invoked from a calling function has its own and
separate workspace (sandbox)
• A script does not lead to a new workspace (unlike a function),
but lives in the workspace from which it was invoked
Variable Types in MATLAB
• Local Variables
• In general, a variable in MATLAB has local scope, that is, it’s only
available in its workspace
• The variable disappears when the workspace ceases to exist
• Recall that a script does not define a new workspace – be careful,
otherwise you can step on variables defined at the level where the
script is invoked
• Since a function defines its own workspace, a variable defined in a
function is local to that function
• Variables defined outside the function should be passed to function
as arguments. Furthermore, the arguments are passed by value
• Every variable defined in the subroutine, if to be used outside the
body of the function, should be returned back to the calling
workspace
Variable Types in MATLAB
• Global Variables
• These are variables that are available in multiple workspaces
• They have to be explicitly declared as being global
• Not going to expand on this, since using global variables is a bad
programming practice
while Loops
eps
eps == 1;
1;
while
while (1+eps)
(1+eps) >> 11
eps
eps == eps/2;
eps/2;
end
end
eps
eps
Flow Control Statements
aa == zeros(k,k)
zeros(k,k) %% Preallocate
Preallocate matrix
matrix
for
for mm == 1:k
1:k
method
method == 'Bilinear';
'Bilinear';
...
... (some
(some code
code here)...
here)...
switch
switch lower(method)
lower(method)
case
case {'linear','bilinear'}
{'linear','bilinear'}
disp('Method
disp('Method is
is linear')
switch case
case 'cubic'
'cubic'
linear')
Statement: disp('Method
disp('Method is
otherwise
otherwise
is cubic')
cubic')
disp('Unknown
disp('Unknown method.')
method.')
end
end
Method
Method is
is linear
linear
Editing and Debugging M-Files
The Editor/Debugger
Debugging M-Files
Types of Errors (Syntax Error and Runtime Error)
Setting Breakpoints
Stepping Through
Continue, Go Until Cursor, Step, Step In, Step Out
Examining Values
Selecting the Workspace
Viewing Datatips in the Editor/Debugger
Evaluating a Selection
Debugging
Select
Workspace
Set Auto-
Breakpoints
tips
Importing and Exporting Data
Using the Import Wizard
save
save fname
fname load
load fname
fname
save
save fname
fname xx yy zz load
load fname
fname xx yy zz
save
save fname
fname -ascii
-ascii load
load fname
fname -ascii
-ascii
save
save fname
fname -mat
-mat load
load fname
fname -mat
-mat
Input/Output for Text File
Suppose the text file stars.dat contains data in the following form:
Jack Nicholson 71 No Yes 1.77
Helen Hunt 45 No No 1.73
for k=1:n
xm = a + 0.5*(b-a); % Minimize roundoff in computing the midpoint
fm = xm - xm^(1/3) - 2; % f(x) at midpoint
fprintf('%3d %12.8f %12.8f %12.8f %12.3e\n',k,a,xm,b,fm);
if sign(fm)==sign(fa) % Root lies in interval [xm,b], replace a
a = xm;
fa = fm;
else % Root lies in interval [a,xm], replace b
b = xm;
fb = fm;
end
end
Other Tidbits
The “inline” Utility
• inline function »» ff ==
inline('3*sin(2*x.^2)','x')
inline('3*sin(2*x.^2)','x')
ff ==
Use char function Inline
Inline function:
function:
to convert inline f(x)
f(x) == 3*sin(2*x.^2)
3*sin(2*x.^2)
object to string »» f(2)
f(2)
ans
ans ==
2.9681
2.9681
• Numerical Integration using quad
»» QQ == quad('1./(x.^3-2*x-5)',0,2);
quad('1./(x.^3-2*x-5)',0,2);
»» FF == inline('1./(x.^3-2*x-5)');
inline('1./(x.^3-2*x-5)');
»» QQ == quad(F,0,2);
quad(F,0,2);
»» QQ == quad('myfun',0,2)
quad('myfun',0,2)
Note:
quad function use adaptive function y = myfun(x)
[initialtime finaltime]
function dydt=myfunc(t,y)
dydt=zeros(2,1);
dydt(1)=y(2);
dydt(2)=(1-y(1)^2)*y(2)-y(1);
»» [t,y]=ode45('myfunc',[0
[t,y]=ode45('myfunc',[0 20],[2;0])
20],[2;0])
3
Note:
1
Editing Plots
Property Editor
Handle Graphics
2-D Plotting
color line marker
Syntax:
plot(x1,
plot(x1, y1,
y1, 'clm1',
'clm1', x2,
x2, y2,
y2, 'clm2',
'clm2', ...)
...)
Example:
x=[0:0.1:2*pi];
x=[0:0.1:2*pi];
y=sin(x);
y=sin(x);
z=cos(x);
z=cos(x);
plot(x,y,x,z,'linewidth',2)
plot(x,y,x,z,'linewidth',2)
title('Sample
title('Sample Plot','fontsize',14);
Plot','fontsize',14);
xlabel('X
xlabel('X values','fontsize',14);
values','fontsize',14);
ylabel('Y
ylabel('Y values','fontsize',14);
values','fontsize',14);
legend('Y
legend('Y data','Z
data','Z data')
data')
grid
grid on
on
Sample Plot
Title
Ylabel
Grid
Legend
Xlabel
Displaying Multiple Plots
Nomenclature:
Figure window – the window in which MATLAB displays plots
Plot – a region of a window in which a curve (or surface) is
displayed
»»subplot(2,2,1);
subplot(2,2,1);
»» ……
»»subplot(2,2,2)
subplot(2,2,2)
»» ...
...
»»subplot(2,2,3)
subplot(2,2,3)
»» ...
...
»»subplot(2,2,4)
subplot(2,2,4)
»» ...
...
The “figure” Command
Use if you want to have several figures open for plotting
Figure
object
UIMenu
objects UIControl
Axes object
objects
Surface
object
Line
objects
Text
objects
Obtaining an Object’s Handle
1. Upon Creation
h_line = plot(x_data, y_data, ...)
2. Utility Functions
What is the current object?
0 - root object handle • Last object created
OR
gcf - current figure handle
• Last object clicked
gca- current axis handle
gco- current object handle
3. h_obj
FINDOBJ
= findobj(h_parent, 'Property', 'Value', ...)
What is GUI?
What is figure and *.fig file?
Using guide command
GUI controls
GUI menus
Axes static text
Frames
Checkbox Slider
Edit text
Property Inspector
Result Figure
Character String
Manipulation
Character Arrays (Strings)
»» str
str == 'Hi
'Hi there,'
there,'
str
str ==
Hi
Hi there,
there,
»» str2
str2 == 'Isn''t
'Isn''t MATLAB
MATLAB great?'
great?'
str2
str2 ==
Isn't
Isn't MATLAB
MATLAB great?
great?
Numeric Arrays
Multidimensional Arrays
Structures and Cell Arrays
Multidimensional Arrays
The first references array dimension
1, the row.
»» AA == pascal(4);
pascal(4);
The second references dimension 2, » A(:,:,2) = magic(4)
» A(:,:,2) = magic(4)
the column. A(:,:,1)
A(:,:,1) ==
The third references dimension 3, 11 11 11 11
The page. 11 22 33 44
1 0 0 0 11 33 66 10
10
0 1 0 0
11 44 10
10 20
20
0 0 1 0
0 0 0 1 A(:,:,2)
A(:,:,2) ==
16
16 22 33 13
13
0 0 0 0 Page N
55 11
11 10
10 88
16 20 30 130 0
110 1
100 80 0 99 77 66 12
12
1 15 1
9 70 60 120 0
44 14 15 11
1 2 3 4 14 15
1 3
4 14 15
6 10
1
»» A(:,:,9)
A(:,:,9) ==
1 4 10 20 diag(ones(1,4));
diag(ones(1,4));
Page 1
Structures
•Arrays with named data containers called fields.
»» patient.name='John
patient.name='John Doe';
Doe';
»» patient.billing
patient.billing == 127.00;
127.00;
»» patient.test=
patient.test= [79
[79 75
75 73;
73;
180
180 178
178 177.5;
177.5;
220
220 210
210 205];
205];
»» A(1,1)
A(1,1) == {[1
{[1 44 3;
3;
00 55 8;
8;
77 22 9]};
9]};
»» A(1,2)
A(1,2) == {'Anne
{'Anne Smith'};
Smith'};
»» A(2,1)
A(2,1) == {3+7i};
{3+7i};
»» A(2,2)
A(2,2) == {-pi:pi/10:pi};
{-pi:pi/10:pi};