Title: MATLAB
1????? MATLAB ???? ??????? ??? ????? ????
2- MATLAB Matrix Laboratory
- Usage
- Math and computation Algorithm
- development Data acquisition Modeling
simulation, and prototyping - Data analysis exploration, and visualization
- Scientific and engineering graphics
- Application development, including graphical user
interface building -
3Development Environment
4Desktop Tools
5Desktop Tools
- Start easy access to tools, demos, and
documentation.
6Current Directory Browser
file you want to run must either be in the
current directory or on the search path
7Workspace Browser
8Editor/Debugger
- M-files are programs you write to run MATLAB
functions.
9Matrix
- To enter a matrix, simply type in the Command
Window - A 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
- MATLAB displays the matrix you just entered.
- A
- 16 3 2 13
- 5 10 11 8
- 9 6 7 12
- 4 15 14 1
10Transpose
- So A'
- produces
- ans
- 16 5 9 4
- 3 10 6 15
- 2 11 7 14
- 13 8 12 1
A 16 3 2 13 5 10 11
8 9 6 7 12 4 15 14
1
11Diagonal Elements
- diag(A)
- produces
- ans
- 16
- 10
- 7
- 1
A 16 3 2 13 5 10 11
8 9 6 7 12 4 15 14
1
12Assigning a new Value to an Element
- X(4,4) 17
- X
- 16 3 2 13
- 5 10 11 8
- 9 6 7 12
- 4 15 14 17
A 16 3 2 13 5 10 11
8 9 6 7 12 4 15 14
1
13Storing an Element
A 16 3 2 13 5 10 11
8 9 6 7 12 4 15 14
1
14The Colon Operator
- The expression 110 is a row vector containing
the integers from 1 to 10 - 1 2 3 4 5 6 7 8
9 10 - To obtain nonunit spacing, specify an increment.
For example, 100-750 is - 100 93 86 79 72 65 58 51
15The Colon Operator
- Subscript expressions involving colons refer to
portions of a matrix. - A(1k , j)
- is the first k elements of the jth column of A
- colon by itself refers to all the elements in a
row or column of a matrix .
A( , 1) A( 2 , )
16Some Other Good Operations
- To swap the two middle columns.
- A B(,1 3 2 4)
- To Erase an entire row or column
- A(1,)
- To Add a new row or column
- BA1 2 1 5
-
17Variable
- MATLAB does not require any type declarations or
dimension statements. - the variable already exists, MATLAB changes its
contents - MATLAB is case sensitive
- To view the matrix assigned to any variable,
simply enter the variable name
18Format
- All computations in MATLAB are done in double
precision. - FORMAT may be used to switch between
different output - display formats as follows
-
- FORMAT Default. Same as SHORT.
-
- FORMAT SHORT Scaled fixed point format with 5
digits - FORMAT LONG Scaled fixed point format
with 15 digits - FORMAT HEX Hexadecimal format.
19Cell Arrays
- They are multidimensional arrays whose elements
are copies of other arrays.
If you subsequently change A, nothing happens to C
Example gtgtC A sum(A) prod(prod(A)) ans C
4x4 double 1x4 double
20922789888000
20useful constants.
- Pi 3.14159265...
- i Imaginary unit sqrt(-1)
- j Same as i
- eps Floating-point relative precision 2 -52
- realmin Smallest floating-point number, 2-1022
- realmax Largest floating-point number, 2-21023
- Inf Infinity
- NaN Not-a-number
21Operations
- Addition
- - Subtraction
- Multiplication
- / Division
- \ Left division (described in "Matrices and
Linear Algebra" in the MATLAB
documentation) - Power
- Complex conjugate transpose
- ( ) Specify evaluation order
22Example
gtgt3/10 ans 0.3000 gtgt 10\3 ans
0.3000
- 1j 22j'
- ans
- 1.0000 - 1.0000i
- 2.0000 - 2.0000i
23- rho (1sqrt(5))/2
- rho
- 1.6180
- a abs(34i)
- a
- 5
- z sqrt(besselk(4/3,rho-i))
- z
- 0.3730 0.3214i
huge exp(log(realmax)) huge
1.7977e308 toobig pihuge toobig Inf
24Generating Matrices
- Z zeros(2,4)
- Z
- 0 0 0 0
- 0 0 0 0
- F 5ones(3,3)
- F
- 5 5 5
- 5 5 5
- 5 5 5
N fix(10rand(1,10)) N 4 9 4
4 8 5 2 6 8 0 R
randn(4,4) R 1.0668 0.2944 -0.6918
-1.4410 0.0593 -1.3362 0.8580 0.5711
-0.0956 0.7143 1.2540 -0.3999
-0.8323 1.6236 -1.5937 0.6900
25Some Useful functions
- A'
- d det(A)
- X inv(A)
- e eig(A)
- poly(A)
- sin(x)
- sinh(x)
- asin(x)
26Array Operators
- Addition
- - Subtraction
- . Element-by-element multiplication
- ./ Element-by-element division
- .\ Element-by-element left division
- . Element-by-element power
- .' Unconjugated array transpose
27Example
- n (09)'
- Then pows n n.2 2.n
- builds a table of squares and powers of 2.
- pows
- 0 0 1
- 1 1 2
- 2 4 4
- 3 9 8
- 4 16 16
- 5 25 32
- 6 36 64
- 7 49 128
- 8 64 256
- 9 81 512
28- gtgt a1 2 3 4
- gtgt b1 2 3 4'
- gtgt ab
- ans
- 30
- gtgt ba
- ans
- 1 2 3 4
- 2 4 6 8
- 3 6 9 12
- 4 8 12 16
- gtgt a.b'
- ans
- 1 4 9 16
29- B
- 7.5 -5.5 -6.5 4.5
- -3.5 1.5 2.5 -0.5
- 0.5 -2.5 -1.5 3.5
- -4.5 6.5 5.5 -7.5
- gtgtB(12,23) 0
- B
- 7.5 0 0 4.5
- -3.5 0 0 -0.5
- 0.5 -2.5 -1.5 3.5
- -4.5 6.5 5.5 -7.5
30Geraphics
- PLOT
- x 0pi/1002pi
- y sin(x)
- plot(x,y)
- xlabel('x 02\pi')
- ylabel('Sine of x')
- title('Plot of the Sine Function','FontSize',12)
31(No Transcript)
32Multiple Data Sets in One Graph
- y2 sin(x-.25)
- y3 sin(x-.5)
- plot(x,y,x,y2,x,y3)
33(No Transcript)
34Colors
- 'c cyan
- 'mmagenta
- 'y yellow
- 'r red
- 'g green
- 'b blue
- 'w white
- 'kblack
35plot(x,y,'ks')
36plot(x,y,'kgt')
37plot(x,y,'r')
38This example plots the data twice using a
different number of points for the dotted line
and marker plots.
- x1 0pi/1002pi
- x2 0pi/102pi
- plot(x1,sin(x1),'r',x2,sin(x2),'r')
39(No Transcript)
40Complex Data
- When the arguments to plot are complex, the
imaginary part is ignored - For the special case of giving the plot a single
complex argument, the command is a shortcut for a
plot of the real part versus the imaginary part. - Therefore, plot(Z) where Z is a complex vector
or matrix, is equivalent to plot(real(Z),imag(Z))
41Adding Plots to an Existing Graph
- hold on
- Example
- x,y,z peaks
- contour(x,y,z,20,'k')
- hold on
- pcolor(x,y,z)
- shading interp
- hold off
42Multiple Plots in One Figure
- subplot(m,n,p)
- Example
- t 0pi/102pi
- X,Y,Z cylinder(4cos(t))
- subplot(2,2,1) mesh(X)
- subplot(2,2,2) mesh(Y)
- subplot(2,2,3) mesh(Z)
- subplot(2,2,4) mesh(X,Y,Z)
43(No Transcript)
44Setting Axis
- axis(xmin xmax ymin ymax zmin zmax)
- axis auto
- axis on
- axis off
- grid on
- grid off
45Example
- t -pipi/100pi
- y sin(t)
- plot(t,y)
- axis(-pi pi -1 1)
- xlabel('-\pi \leq \itt \leq \pi')
- ylabel('sin(t)')
- title('Graph of the sine function')
- text(1,-1/3,'\itNote the odd symmetry.')
46(No Transcript)
47Mesh and Surface Plots
- Mesh (x,y,z)
- produces wireframe surfaces that color only the
lines connecting the defining points. - surf (x,y,z)
- displays both the connecting lines and the faces
of the surface in color.
48- X,Y meshgrid(-8.58)
- R sqrt(X.2 Y.2) eps
- Z sin(R)./R
- mesh(X,Y,Z,'EdgeColor','black')
49transparency
50Surf Example
surf(X,Y,Z) colormap hsv colorbar
51View
view(az,el) view(az,el)
52Surface Plots with Lighting
- surf(X,Y,Z,'FaceColor','red','EdgeColor','none')
- camlight left lighting phong
- view(-15,65)
53Flow Control
- if rem(n,2) 0
- .
- elseif rem(n,4) 0
-
- else
- .
- end
54Important!
- when A and B are matrices, A B does not test
if they are equal, it tests where they are equal
the result is another matrix of 0's and 1's
showing element-by-element equality. - Solution
- if isequal(A,B), ...
55Some Other Helpful Functions
- Isequal(A,B,)
- Determine if arrays are numerically equal
- Isempty(A)
- Determine if item is an empty array
- isequalwithequalnans(A,B,...)
- Determine if arrays are numerically equal,
treating NaNs as equal - ismember(A,S)
- Detect members of a specific set
- isnumeric(A)
- Returns logical true (1) if A is a numeric
array and logical false (0) otherwise.
56Some Other Helpful Functions
- isprime(A)
- returns an array the same size as A containing
logical true (1) for the elements of A which are
prime. - isreal(A)
- returns logical false (0) if any element of
array A has an imaginary component, even if the
value of that component is 0. - ischar(A)
- ischar(A) returns logical true (1) if A is a
character array and logical false (0) otherwise.
57- all(A)
- If A is a vector, all(A) returns logical true
(1) if all of the elements are nonzero, and
returns logical false (0) if one or more elements
are zero. -
- If A is a matrix, all(A) treats the columns of A
as vectors, returning a row vector of 1s and 0s.
58- B any(A)
- If A is a vector, any(A) returns logical true
(1) if any of the elements of A are nonzero, and
returns logical false (0) - if all the elements are zero.
- If A is a matrix, any(A) treats the columns of A
as vectors, returning a row vector of 1s and 0s.
59Example
- gtgtA 0.53 0.67 0.01 0.38 0.07 0.42 0.69
- B (A lt 0.5)
- Ans
- 0 0 1 1 1 1 0
- gtgtall(B)
- Ans 0
- gtgtany(B)
- Ans 1
???? ???????
60Relational Operators
EXAMPLE gtgtX 5ones(3,3) gtgtX gt 1 2 3 4 5 6
7 8 10 ans 1 1 1 1 1 0
0 0 0
- A lt B
- A gt B
- A lt B
- A gt B
- A B
- A B
61Logical Operators
The precedence for the logical operators
The truth table
The second operand is evaluated only when the
result is not fully determined by the first
operand.
62Example
Logical Operation on Elements
Short Circuit and
- gtgtu 0 0 1 1 0 1
- gtgtv 0 1 1 0 0 1
- gtgtu v
- ans
- 0 1 1 1 0 1
to avoid generating a warning when the divisor,
b, is zero. x (b 0) (a/b gt 18.5)
63Flow Control
- switch (rem(n,4)0) (rem(n,2)0)
- case 0
- .
- case 1
- .
- case 2
-
- otherwise
- error('This is impossible')
- end
64Important!
- 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.
65Flow Control
- for variable scalar1 step scalar2
- statement 1
- ...
- statement n
- end
Example a zeros(k,k) Preallocate
matrix for m 1k for n 1k
a(m,n) 1/(mn -1) end end
66- while expression
- statements
- End
The statements are executed while the real part
of expression has all nonzero elements.
67Two Useful Functions for Loops
- Continue
- Passes control to the next iteration of for or
while loop - Break
- statement lets you exit early from a for or
while loop.
68Characters and Numbers
- To define a string
- gtgts 'Hello
- characters are stored as numbers, but not in
floating-point format. - To see the characters as numbers
- gtgta double(s)
- a
- 72 101 108 108 111
- To reverses the conversion
- gtgts char(a)
69M-files
- Scripts, which do not accept input arguments or
return output arguments. They operate on data in
the workspace. - Functions, which can accept input arguments and
return output arguments. Internal variables are
local to the function.
70Functions
- Checks to see if the name is a variable.
- Checks to see if the name is an internal function
(eig, sin) that was not overloaded. - Checks to see if the name is a local function
(local in sense of multifunction file). - Checks to see if the name is a function in a
private directory. - Locates any and all occurrences of function in
method directories and on the path. Order is of
no importance. - At execution, MATLAB
- Checks to see if the name is wired to a specific
function (2, 3, 4 above) - Uses precedence rules to determine which instance
from 5 above to call (we may default to an
internal MATLAB function). Constructors have
higher precedence than anything else.
71Functions
- nargin and nargout indicate how many input or
output arguments, respectively, a user has
supplied.
if nargout 0 plot(x,y) else x0 x
y0 y end
if nargin lt 5, subdiv 20 end if nargin lt 4,
angl 10 end if nargin lt 3, npts 25 end
72- function x0,y0 myplot(fname,lims,npts,angl,sub
div) - MYPLOT Plot a function.
- MYPLOT(fname,lims,npts,angl,subdiv)
- The first two input arguments are
- required the other three have default
values. - ...
- if nargin lt 5, subdiv 20 end
- if nargin lt 4, angl 10 end
- if nargin lt 3, npts 25 end
- ...
- if nargout 0
- plot(x,y)
- else
- x0 x
- y0 y
- end
function h falling(t) global GRAVITY h
1/2GRAVITYt.2
73A review on Mathematical Functions
- Binary addition AB plus(A,B)
- Unary plus A uplus(A) Binary
- Subtraction A-B minus(A,B)
- Unary minus -A uminus(A) Matrix
- Multiplication AB mtimes(A,B) Array-wise
- Multiplication A.B times(A,B) Matrix right
- Division A/B mrdivide(A,B) Array-wise right
- Division A./B rdivide(A,B) Matrix left
- Division A\B mldivide(A,B) Array-wise left
- Division A.\B ldivide(A,B) Matrix
- Power AB mpower(A,B) Array-wise
- Power A.B power(A,B) Complex
- Transpose A ctranspose(A) Matrix
- Transpose A. transpose(A)
74