Professional Documents
Culture Documents
Examples:
Matrix computations and linear algebra
Solving nonlinear equations
Numerical solution of differential equations
Mathematical optimization
Statistics and data analysis
Signal processing
Modelling of dynamical systems
Solving partial differential equations
Simulation of engineering systems
1
Matlab Basics
• MATLAB Environment
• Getting Help
• Variables
• Vectors, Matrices, and Linear Algebra
• Flow Control / Loops
2
Matlab Basics
Matlab as a calculator
– Type expressions at the >>, and press return
– Result is computed, and displayed as ans
– Use numbers, +, *, /, -, (), sin, cos, exp,
abs, round,…
4
Display Windows (con’t…)
• Graphic (Figure) Window
– Displays plots and graphs
• E.g: surf(magic(30))
– Created in response to graphics commands.
5
Getting Help
• type one of following commands in the
command window:
– help – lists all the help topic
– help command – provides help for the specified
command
• help help – provides information on use of the help
command
– Google… of course
6
Variables
• Variable names:
– Must start with a letter
– May contain only letters, digits, and the underscore “_”
– Matlab is case sensitive, i.e. one & OnE are different variables.
• Assignment statement:
– Variable = number;
– Variable = expression;
7
Variables (con’t…)
• Special variables:
– ans : default variable name for the
result
– pi: = 3.1415926…………
– eps: = 2.2204e-016, smallest amount
by which 2 numbers can differ.
– Inf or inf : , infinity
– NaN or nan: not-a-number
8
Interactive Calculations
9
Examples of expressions
Legal expressions
>> 4
>> 5 + pi
>> 6*sqrt(2)^4-12
>> 6 * sqrt( 2.0) ^ 4 - 12
>> sin(pi/3)^2 + cos(pi/3)^2
>> 1.0/0.0
>> -4/inf
>> 0/0
Illegal expressions
>> 2 4
>> (2,4)
Error messages
– Read them carefully – a large portion of the time you will quickly figure out what is wrong
10
Variables
Use names to assign result of an expression to a variable
– Variables do not need to be declared before assignment
A semicolon at the end of the RHS expression suppresses the display, but the
assignment still takes place.
11
Examples of Variables and Assignment
Legal
>> A = sqrt(13)
>> B = exp(2);
>> A = 2*B
>> A = A + 1
>> C = tan(pi/4)
12
The “workspace”
13
Comparison (as opposed to assignment)
>> 5==sqrt(25)
>> E = 1.72>tan(pi/3)
14
Saving the workspace
When you “quit” Matlab, the variables in the workspace are erased from memory. If
you need them for later use, you must save them.
You can save all variables (or just some of them) to a file using the command
save
>> save
saves all of the variables in the workspace into a file called matlab.mat
(it is saved in the current directory)
15
Loading from a .mat file
load is the opposite of save. It reads a .mat file,
putting all variables contained in the .mat file
into the workspace
>> load
loads all of the variables from the file matlab.mat
17
Functions
MATLAB has many built-in functions.
18
MATLAB Special Variables
19
Arrays in Matlab
• Vectors
• Matrices
• Solutions to Systems of Linear Equations.
20
MATLAB Matrices
• MATLAB treats all variables as matrices. For our purposes a matrix can be
thought of as an array, in fact, that is how it is stored.
• Vectors are special forms of matrices and contain only one row OR one
column.
• Scalars are matrices with only one row AND one column
21
Arrays
A rectangular arrangement of numbers is called an
array.
22
Scalars, Vectors and Arrays
1-by-1 arrays are also called scalars
23
Creating Arrays
Horizontal and Vertical Concatenation (ie., “stacking”)
– Square brackets, [, and ] to define arrays
– Spaces (and/or commas) to separate columns
– Semi-colons to separate rows
Example
3 4 5
>> [ 3 4 5 ; 6 7 8 ] is the 2-by-3 array 6 7 8
zeros(n,m)
– a n-by-m double array, each entry is equal to 0
rand(n,m)
– a n-by-m double array, each entry is a random number between 0 and
1.
Examples
>> A = ones(2,3);
>> B = zeros(3,4);
>> C = rand(2,5);
25
The colon ”:” convention
The “: (colon) convention” is used to create row vectors,
whose entries are evenly spaced.
26
F:J:L with J<0 (decrementing)
You can also decrement (ie., J<0), in which case L
should be less than F.
27
The SIZE command
If A is an array, then size(A) is a 1-by-2 array.
– The (1,1) entry is the number of rows of A
– The (1,2) entry is the number of columns of A
If A is an array, then
size(A,1) is the number of rows of A
size(A,2) is the number of columns of A
Example
>> A = rand(5,6);
>> B = size(A)
>> size(A,2)
28
Accessing single elements of a vector
If A is a vector (ie, a row or column vector), then
A(1) is its first element,
A(2) is its second element,…
Example
>> A = [ 3 4.2 -7 10.1 0.4 -3.5 ];
>> A(3)
>> Index = 5;
>> A(Index)
This syntax can be used to assign an entry of A. Recall assignment
>> VariableName = Expression
An entry of an array may also be assigned
>> VariableName(Index) = Expression
So, change the 4’th entry of A to the natural logarithm of 3.
>> A(4) = log(3);
29
Accessing multiple elements of a
vector
A(3) refers to the 3rd entry of A. However, the index need not be a
single number.
30
Assigning multiple elements of a
vector
In an assignment to multiple entries of a vector
>> A(Index) = Expression
the right-hand side expression should be a scalar, or the same
size as the array being referenced by A(Index)
31
Accessing elements and parts of arrays
If M is an array, then M(3,4) is
– the element in the (3rd row , 4th column) of M
In an assignment
>> M(RIndex,CIndex) = Expression
the right-hand side expression should be a scalar, or the same
size as the array being referenced by M(RIndex,CIndex)
Do some examples
32
Layout in memory
The entries of a numeric array in Matlab are
stored together in memory in a specific order.
>> A = [ 3.4 4.2 8 ; -6.7 12 0.75 ];
represents the array Name = ‘A’
3 .4 4 .2 8 Size = [2 3];
6 .7 12 0 .75
Data = 3.4
-6.7
4.2
Somewhere in memory, Matlab has 12
8
0.75
Workspace: Base
RESHAPE
RESHAPE changes the size, but not the values or order of the data in memory.
>> A = [ 3 4.2 8 ; -6.7 12 0.75 ];
>> B = reshape(A,[3 2]);
The result (in memory is)
35
: as a row or column index
Suppose A is an N-by-M array, and a reference of the
form
A(RIndex,CIndex)
Example:
>> M = rand(4,5);
>> M(:,[1 3 5])
36
LINSPACE and LOGSPACE
>> linspace(A,B,N) is a 1-by-N row vector of evenly
spaced numbers, starting at A, and ending at B
Examples
>> linspace(1,4,6)
>> logspace(-1,1,5)
>> log10(logspace(-1,1,5))
37
MATLAB Math & Assignment Operators
- (unary) + (unary)
Addition + a + b
Subtraction - a - b
Assignment = a = b (assign b to a)
38
Vectors and Matrices
39
Polynomial example
Find polynomial roots:
1.2 x 3 0.5 x 2 4 x 10 0
>> x=[1.2,0.5,4,10]
x =
>> roots(x)
ans =
0.59014943179299 + 2.20679713205154i
0.59014943179299 - 2.20679713205154i
-1.59696553025265
40
Vectors
Example:
>> x = [ 0 0.25*pi 0.5*pi 0.75*pi pi ] x is a row vector.
x=
0 0.7854 1.5708 2.3562 3.1416
>> y = [ 0; 0.25*pi; 0.5*pi; 0.75*pi; pi ] y is a column vector.
y=
0
0.7854
1.5708
2.3562
3.1416
41
Vectors (con’t…)
• Vector Addressing – A vector element is addressed in MATLAB with an integer index
enclosed in parentheses.
• Example:
>> x(3)
ans =
1.5708 3rd element of vector x
• The colon notation may be used to address a block of
elements.
(start : increment : end)
start is the starting index, increment is the amount to add to each successive index, and end
is the ending index. A shortened format (start : end) may be used if increment is 1.
• Example:
>> x(1:3) 1st to 3rd elements of vector x
ans =
0 0.7854 1.5708 NOTE: MATLAB index starts at 421.
Vectors (con’t…)
Some useful commands:
y = x’ transpose of vector x
dot (x, y) returns the scalar dot product of the vector x and y.
43
Matrices
A Matrix array is two-dimensional, having both multiple rows and multiple columns,
similar to vector arrays:
it begins with [, and end with ]
spaces or commas are used to separate elements in a row
semicolon or enter is used to separate rows.
•Example:
A is an m x n matrix.
•>> f = [ 1 2 3; 4 5 6]
f=
1 2 3
4 5 6
Example: recall:
f=
>> f(2,3)
1 2 3
ans = 4 5 6
h=
6
2 4 6
>> h(:,1) 1 3 5
ans =
2
1 45
Matrices (con’t…)
more commands
Transpose B = A’
Identity Matrix eye(n) returns an n x n identity matrix
eye(m,n) returns an m x n matrix with ones on the main
diagonal and zeros elsewhere.
Addition and subtraction C=A+B
C=A– B
Scalar Multiplication B = A, where is a scalar.
Matrix Multiplication C = A*B
Matrix Inverse B = inv(A), A must be a square matrix in this case.
rank (A) returns the rank of the matrix A.
Matrix Powers B = A.^2 squares each element in the matrix
C = A * A computes A*A, and A must be a square matrix.
Determinant det (A), and A must be a square matrix.
A, B, C are matrices, and m, n, are scalars.
46
Solutions to Systems of Linear Equations
• Example: a system of 3 linear equations with 3 unknowns (x1, x2, x3):
3x1 + 2x2 – x3 = 10
-x1 + 3x2 + 2x3 = 5
x1 – x2 – x3 = -1
Let :
3 2 1 x1 10
A 1 3 2 x x2 b 5
1 1 1 x3 1
Ax = b
47
Solutions to Systems of Linear Equations (con’t…)