MATLAB Basics
description
Transcript of MATLAB Basics
1
MATLABBasics
2
MATLAB Documentation
http://www.mathworks.com/access/helpdesk/help/techdoc/
http://www.sosmath.com/matrix/matrix.html
Matrix Algebra
3
What is MATLAB?MATLAB (Matrix laboratory) is an
interactive software system. It integrates mathematical computing, visualization, and a powerful language to provide a flexible environment for technical computing. Typical uses include
• 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
4
The MATLAB Product Family
The MathWorks offers a set of integrated products for data analysis, visualization, application development, simulation, design, and code generation. MATLAB is the foundation for all the MathWorks products.
Demos: http://www.mathworks.com/products/matlab/demos.html
5
Using MATLAB in CUHK
• With Windows Version
• With Unix Version
• 200 concurrent licenses using throughout the Departments in CUHK
• Licenses controlled by a License Server
• Used by more than 10 Departments in Engineering and Science Faculties
6
Starting MATLAB
• Windows double-click the MATLAB shortcut icon on your
Windows desktop.
• UNIXtype matlab at the operating system prompt.
• After starting MATLAB, the MATLAB desktop opens.
7
Quitting MATLAB
• select Exit MATLAB from the File menu in the desktop, or type quit in the Command Window.
8
MATLAB Desktop
9
Command Window
10
Command History
11
Current Directory Browser
12
»workspace
Command line variables saved in MATLAB workspace
Workspace Browser
13
Window Preferences
14
Getting help
• MATLAB Documentation
• >> helpdesk or doc– Online Reference (HTML / PDF)
– Solution Search Engine
– Link to The MathWorks (www.mathworks.com)• FTP site & latest documentation
• Submit Questions, Bugs & Requests
• MATLAB access - MATLAB Digest / Download upgrades
15
Using Help
• The help command >> help• The help window >> helpwin
• The lookfor command >> lookfor» lookfor exampleDDEX1 Example 1 for DDE23.DDEX1DE Example of delay differential equations for solving with DDE23.DDEX2 Example 2 for DDE23.ODEEXAMPLES Browse ODE/DAE/BVP/PDE examples.....
» help lookforLOOKFOR Search all M-files for keyword. LOOKFOR XYZ looks for the string XYZ in the first comment line (the H1 line) of the HELP text in all M-files found on MATLABPATH. For all files in which a match occurs, LOOKFOR displays the H1 line.....
» lookfor exampleDDEX1 Example 1 for DDE23.DDEX1DE Example of delay differential equations for solving with DDE23.DDEX2 Example 2 for DDE23.ODEEXAMPLES Browse ODE/DAE/BVP/PDE examples.....
» help lookforLOOKFOR Search all M-files for keyword. LOOKFOR XYZ looks for the string XYZ in the first comment line (the H1 line) of the HELP text in all M-files found on MATLABPATH. For all files in which a match occurs, LOOKFOR displays the H1 line.....
16
Calculations at the Command Line
» -5/(4.8+5.32)^2ans = -0.0488» (3+4i)*(3-4i)ans = 25» cos(pi/2)ans = 6.1230e-017» exp(acos(0.3))ans = 3.5470
» -5/(4.8+5.32)^2ans = -0.0488» (3+4i)*(3-4i)ans = 25» cos(pi/2)ans = 6.1230e-017» exp(acos(0.3))ans = 3.5470
» a = 2;
» b = 5;
» a^b
ans =
32
» x = 5/2*pi;
» y = sin(x)
y =
1
» z = asin(y)
z =
1.5708
» a = 2;
» b = 5;
» a^b
ans =
32
» x = 5/2*pi;
» y = sin(x)
y =
1
» z = asin(y)
z =
1.5708
Results assigned to “ans” if name not specified
() parentheses for function inputs
Semicolon suppresses screen output
MATLAB as a calculator Assigning Variables
Numbers stored in double-precision floating point format
17
>> 2 +3 ( 5 ) >> 2 *3 ( 6 ) >> 1/2 ( 0.5000 )>> 2 ^3 ( 8 )>> 0/1 ( 0 )>> 1/0 ( Warning: Divide by zero. Inf )>> 0/0 ( NaN )
Up/Down arrow to recall previous commandsOr use Ctrl+C and Ctrl+V to reuse commands
Simple Mathematics
18
cos(x), sin(x), tan(x), asinh(x), atan(x), atanh(x), …
ceil(x): smallest integer which exceeds x, e.g. ceil(-3.9) returns -3floor(x): largest integer not exceeding x, e.g. floor(3.8) returns 3
date, exp(x), log(x), log10(x), sqrt(x), abs(x)
max(x): maximum element of vector xmin(x): minimum element of vector xmean(x): mean value of elements of vector xsum(x): sum of elements of vector xsize(a): number of rows and columns of matrix a
Some Common Functions
19
rand: random number in the interval [0, 1)
realmax: largest positive floating point numberrealmin: smallest positive floating point number
rem(x, y): remainder when x is divided by y, e.g. rem(19,5) returns 4
sign(x): returns -1, 0 or 1 depending on whether x is negative, zero or positive
sort(x): sort elements of vector x into ascending order (by column if x is a matrix)
Some Common Functions
20
A Matlab program can be edited and saved (using Notepad) to a file with .m extension. It is also called a M-file, a script file or simply a script.
When the name of the file is entered in >>, Matlab (or right-click and then run) carries out each statement in the file as if it were entered at the prompt. You are encouraged to use this method.
The M-file
21
22
23
Basic Concepts
a = 2;
b = 7;
c = a + b;
disp(c)
Variables such as a, b and c are called scalars; they are single-valued.
MATLAB also handles vectors and matrices, which are the key to many powerful features of the language.
24
Vectors
A vector is a special type of matrix, having only one row, or one column.
x = [1 3 0 -1 5]
a = [5, 6, 8]
y = 1:10 (elements are the integers 1, 2, …, 10)
z = 1:0.5:4 (elements are the values 1, 1.5, …, 4 in increments of 0.5)
x’ is the transpose of x. Or you can do it directly: [1 3 0 -1 5]’.
25
Working with Matrices
MATLAB == MATrix LABoratory
26
The Matrix in MATLAB
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1
2
Rows (m) 3
4
5
Columns(n)
1 2 3 4 51 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
A = A (2,4)
A (17)
Rectangular Matrix:
Scalar: 1-by-1 arrayVector: m-by-1 array
1-by-n arrayMatrix: m-by-n array
where m, n can be 1, 2, 3, 4, …
27
Any MATLAB expression can be entered as a matrix element
Entering Numeric Arrays
» a=[1 2;3 4]
a =
1 2
3 4
» b=[-2.8, sqrt(-7), (3+5+6)*3/4]
b =
-2.8000 0 + 2.6458i 10.5000
» b(2,5) = 23
b =
-2.8000 0 + 2.6458i 10.5000 0 0
0 0 0 0 23.0000
» a=[1 2;3 4]
a =
1 2
3 4
» b=[-2.8, sqrt(-7), (3+5+6)*3/4]
b =
-2.8000 0 + 2.6458i 10.5000
» b(2,5) = 23
b =
-2.8000 0 + 2.6458i 10.5000 0 0
0 0 0 0 23.0000
Row separator:semicolon (;)
Column separator:space / comma (,)
Use square brackets [ ]
Matrices must be rectangular. (Set undefined elements to zero)
28
Entering Numeric Arrays - cont.
» w=[1 2;3 4] + 5w = 6 7 8 9» x = 1:5
x = 1 2 3 4 5» y = 2:-0.5:0
y = 2.0000 1.5000 1.0000 0.5000 0 » z = rand(2,4)
z =
0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185
» w=[1 2;3 4] + 5w = 6 7 8 9» x = 1:5
x = 1 2 3 4 5» y = 2:-0.5:0
y = 2.0000 1.5000 1.0000 0.5000 0 » z = rand(2,4)
z =
0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185
Scalar expansion
Creating sequences:colon operator (:)
Utility functions for creating matrices.(Ref: Utility Commands)
29
Numerical Array Concatenation - [ ]
» a=[1 2;3 4]
a =
1 2
3 4
» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24
>> size(cat_a)ans =
6 4
» a=[1 2;3 4]
a =
1 2
3 4
» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24
>> size(cat_a)ans =
6 4
Use [ ] to combine existing arrays as matrix “elements”
Row separator:semicolon (;)
Column separator:space / comma (,)
Use square brackets [ ]
The resulting matrix must be rectangular.
4*a
30
Array Subscripting / Indexing
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1
2
3
4
5
1 2 3 4 51 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
A =
A(3,1)A(3)
A(1:5,5)A(:,5) A(21:25)
A(4:5,2:3)A([9 14;10 15])
• Use () parentheses to specify index• colon operator (:) specifies range / ALL• [ ] to create matrix of index subscripts• ‘end’ specifies maximum index value
A(1:end,end) A(:,end)A(21:end)’
31
Matrix Multiplication
• Inner dimensions must be equal
• Dimension of resulting matrix = outermost dimensions of multiplied matrices
• Resulting elements = dot product of the rows of the 1st matrix with the columns of the 2nd matrix» a = [1 2 3 4; 5 6 7 8];
» b = ones(4,3);
» c = a*b
c =
10 10 10 26 26 26
» a = [1 2 3 4; 5 6 7 8];
» b = ones(4,3);
» c = a*b
c =
10 10 10 26 26 26
[2x4]
[4x3]
[2x4]*[4x3] [2x3]
a(2nd row).b(3rd column)
32
Array Multiplication
• Matrices must have the same dimensions
• Dimensions of resulting matrix = dimensions of multiplied matrices
• Resulting elements = product of corresponding elements from the original matrices
Same rules apply for other array operations
» a = [1 2 3 4; 5 6 7 8];
» b = [1:4; 1:4];
» c = a.*b
c =
1 4 9 16 5 12 21 32
» a = [1 2 3 4; 5 6 7 8];
» b = [1:4; 1:4];
» c = a.*b
c =
1 4 9 16 5 12 21 32 c(2,4) = a(2,4)*b(2,4)
33
bal = 15000 * rand;
if bal < 5000rate = 0.09;
elseif bal < 10000rate = 0.12;
elserate = 0.15;
end
newbal = bal + rate + bal;disp(’New balance is: ’)disp(newbal)
Deciding with if
34
for index = j:k
statementsend
for index = j:m:k (m is the increment)statements
end
Repeating with for
35
Create a program in newton.m file to calculate the square root of 2
%NEWTON Newton Method examplea = 2;x = a/2;for i = 1:6 x = (x+a/x)/2; disp (x)end
Square rooting with Newton Method
36
>> newton 1.5000 1.4167 1.4142 1.4142 1.4142 1.4142>> format long>> newton 1.50000000000000 1.41666666666667 1.41421568627451 1.41421356237469 1.41421356237309 1.41421356237309
Running newton.m
37
fprintf formats the output as specified by a format string.
fprintf ('format string', list of variables)fprintf ('filename', 'format string' , list of variables)
balance = 123.45678901;fprintf('New balance: %8.3f', balance)
%8.3f means fixed point over 8 columns altogether (including the decimal point and a possible minus sign), with 3 decimal places (spaces are filled in from the left if necessary).
Input / Output
38
fprintf example (io_1.m)
balance = 12345;rate = 0.09;interest = rate * balance;balance = balance + interest;fprintf('Interest rate: %6.3f New balance: %8.2f\n', rate, balance);
>> io_1Interest rate: 0.090 New balance: 13456.05
>>
Input / Output Examples
39
Input / Output
The input statement gives the user the prompt in the text string and then waits for input from the keyboard. It provides a more flexible way of getting data into a program than by assignment statements which need to be edited each time the data must be changed. It allows you to enter data while a script is running.
The general form of the input statement is:
variable = input(’prompt’);
40
Interactive Input (io_2.m)
balance = input('Enter bank balance: ');rate = input('Enter interest rate: ');interest = rate * balance;balance = balance + interest;fprintf('New balance: %8.2f\n', balance);
>> io_2Enter bank balance: 2000Enter interest rate: 0.08New balance: 2160.00>>
Input / Output Examples
41
2-D Plotting
• Specify x-data and/or y-data
• Specify color, line style and marker symbol (clm), default values used if ‘clm’ not specified)
• Syntax:– Plotting single line:
– Plotting multiple lines:plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)
plot(xdata, ydata, 'clm')
42
x = 0 : 10y = 2 * xplot (x, y)plot (x, sin(x))x = 0 : 0.1 :10;pauseplot (x, sin(x))plot (x, sin(x)), grid
2-D Plot – Examples
43
Graphs may be labelled with the following statements:
gtext(’text’): writes a string in the graph window
grid: add/removes grid lines to/from the current graph
text(x, y, ’text’): writes the text at the point specified by x and y
title(’text’): writes the text as a title on top of the graph
xlabel(’text’): labels the x-axis
ylabel(’text’): labels the y-axis
2-D Plot – Labels
44
The function plot3 is the 3-D version of plot. The command plot3(x,y,z) draws a 2-D projection of a line in 3-D through the points whose co-ordinates are the elements of the vectors x, y and z.
plot3(rand(1,10), rand(1,10), rand(1,10))
The above command generates 10 random points in 3-D space, and joins them with lines.
3D Plot - Examples
45
MATLABExercise