You are on page 1of 48

What is MATLAB?

Matlab = Matrix Laboratory

A software environment for interactive numerical computations

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,…

Precedence rules in expressions


– Left-to-right within a precedence group
– Precedence groups are (highest first)
• Highest precedence is parenthesis, then…
• Power (^)
• Multiplication and division (*, /)
• Addition and subtraction (+, -)
3
Display Windows

4
Display Windows (con’t…)
• Graphic (Figure) Window
– Displays plots and graphs
• E.g: surf(magic(30))
– Created in response to graphics commands.

• M-file editor/debugger window


– Create and edit scripts of commands called M-files.

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;

NOTE: when a semi-


• Example:
>> tutorial = 1234; colon ”;” is placed at the
>> tutorial = 1234 end of each command,
tutorial = the result is not displayed.
1234

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

Matlab is interactive, no need to declare variables


>> 2+3*4/2
>> a=5e-3; b=1; a+b

Most elementary functions and constants are already defined


>> cos(pi)
>> abs(1+i)
>> sin(pi)

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 single “equal” sign (=) is the assignment operator,


LHS = RHS
Read this as
– evaluate expression on the right-hand side, and then…
– assign the result to the variable named on the left-hand-side
Therefore
– The right-hand-side needs to be a legal Matlab expression
– The left-hand-side needs to be a single variable name (this will get more
sophisticated later on)

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)

Illegal (all for different reasons)


>> D = sqrt(E) + 1;
>> 3 = E
>> 3*A = 14
>> F = 2 3

12
The “workspace”

All variables that you create are accessible from the


prompt >>

Variables are accessed using their name as a reference

Builtin Matlab commands


>> who
>> whos
are used to see what is in the workspace.

You can clear (ie, erase) variables with the clear


command
>> clear A
clears the variable A from the workspace.

13
Comparison (as opposed to assignment)

Compare the equality of two expressions with a double equal sign, ==


Several arithmetic comparisons are available. Can also compare
– greater than (with >)
– less than (with <)
– greater than or equal (with >=)
– less than or equal (with <=), and
– not equal (with ~=)
The comparison is itself an expression
– Its value is either 1 (true) or 0 (false), and can be used in assignment

>> 5==sqrt(25)
>> E = 1.72>tan(pi/3)

What do you need to know to determine the result of


>> E = 4>5-2
Precedence group is lower than addition and subtraction, so…

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)

>> save Andy


saves all of the variables in the workspace into a file called Andy.mat
>> save Important A B C D*
saves the variables A, B, C and any variable beginning with D in the workspace
into a file called Important.mat

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

>> load Andy


loads all of the variables from the file andy.mat

There are no known security problems with load.


Hence, you can safely send (as attachment),
receive and use .mat files from others.
16
Complex Numbers

All arithmetic in Matlab works on complex numbers as


well.

When you start Matlab, two variables already exist,


and are equal to . They are i and j. It’s
common to overwrite them without even realizing,
but you can always create the number with the
expression sqrt(-1)
>> i
>> sqrt(-1)
>> j
>> 4 + 6j
>> 4 + 6*j
>> C = 1 – 2i;
>> real(C)
>> imag(C)
>> abs(C)
>> angle(C)*180/pi

17
Functions
MATLAB has many built-in functions.

Some math functions are:

acos, acosh acot, acsc, acsch, asec, asech, asin,


asinh, atan, atan2, atanh, cos, cosh, cot, coth, csc,
csch, sec, sech, sin, sinh, tan, tanh, exp, log, log10,
log2, pow2, sqrt, nextpow2, abs, angle, conj, imag,
real, unwrap, isreal, cplxpair, fix, floor, ceil,
round, mod, rem, sign, cart2sph, cart2pol, pol2cart,
sph2cart, factor, isprime, primes, gcd, lcm, rat, rats,
perms, nchoosek, airy, besselj, bessely, besselh,
besseli, besselk, beta, betainc, betaln, ellipj,
ellipke, erf, erfc, erfcx, erfinv, expint, gamma,
gammainc, gammaln, legendre, cross, dot

18
MATLAB Special Variables

ans Default variable name for results


pi Value of 
inf 
NaN Not a number e.g. 0/0
i and j i = j = 1
eps Smallest incremental number
realmin The smallest usable positive real number
realmax The largest usable positive real number

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.

This is a 4-by-2 array.


1 7
It has 4 rows, and 2
4 9 columns.
3 6 The (3,1) entry is the
5 8 entry in the 3rd row,
and 1st column

Later, we will have rectangular arrangement of more


general objects. Those will also be called arrays.

22
Scalars, Vectors and Arrays
1-by-1 arrays are also called scalars

1-by-N arrays are also called row vectors

N-by-1 arrays are also called column vectors

Row and Column vectors are also sometimes just


called vectors

In Matlab, all arrays of numbers are called double arrays.

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
 

If A and B are arrays with the same number of rows, then


>> C = [ A B ] is the array formed by stacking A “next to” B
Once constructed, C does not “know” that it came from two arrays stacked next
to one another. No partitioning information is maintained.

If A and B are arrays with the same number of columns, then


>> [ A ; B ] is the array formed by stacking A “on top of” B

So, [ [ 3 ; 6 ] [ 4 5 ; 7 8 ] ] is equal to [ 3 4 5;6 7 8 ]


24
Creating special arrays
ones(n,m)
– a n-by-m double array, each entry is equal to 1

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.

7:2:18 equals the row vector [ 7 9 11 13 15 17 ]

If F, J and L are numbers with J>0, F ≤ L, then F:J:L creates a


row vector
[ F F+J F+2*J F+3*J … F+N*J ]
where F+N*J ≤ L, and F+(N+1)*J>L

Many times, the increment is 1. Shorthand for F:1:L is F:L

26
F:J:L with J<0 (decrementing)
You can also decrement (ie., J<0), in which case L
should be less than F.

Therefore 6.5:-1.5:0 is the row vector

[ 6.5 5.0 3.5 2.0 0.5 ]

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.

Example: Make a 1-by-6 row vector, and access multiple elements,


giving back row vectors of various dimensions.
>> A = [ 3 4.2 -7 10.1 0.4 -3.5 ];
>> A([1 4 6]) % 1-by-3, 1st, 4th, 6th entry
>> Index = [3 2 3 5];
>> A(Index) % 1-by-4
Index should contain integers. Regardless of whether A is a row or
column, Index can be a row or a column, and Matlab will do the
same thing in both cases. The expressions below are the same.
>> A([2 4 3])
>> A([2;4;3])

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)

Example: Make a 1-by-6 row vector, and access multiple


elements, giving back row vectors of various dimensions.
>> A = [ 3 4.2 -7 10.1 0.4 -3.5 ];
>> A([1 4 6]) = [10 100 1000];
>> Index = [3 2 5];
>> A(Index) = pi;

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

If M is an array, then M([1 4 2],[5 6])


– is a 3-by-2 array, consisting of the entries of M from
• rows [1, 4 and 2]
• columns [5 and 6]

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)

So, A is the array


Name = ‘A’ Name = ‘B’
 3 .4 4 .2 8
Size = [2 3]; Size = [3 2];  6.7 12 0.75
 
Data = 3.4 Data = 3.4
-6.7 -6.7 while B is the array
4.2 4.2
12 12  3 12
8 8  6.7 8
0.75
 
0.75
 4.2 0.75
34
END
Suppose A is an N-by-M array, and a reference of the
form
A(RIndex,CIndex)

Any occurence of the word end in the RIndex is changed


(automatically) to N

Any occurence of the word end in the CIndex is changed


(automatically) to M
Example:
>> M = rand(4,5);
>> M(end,end)
>> M([1 end],[end-2:end])

35
: as a row or column index
Suppose A is an N-by-M array, and a reference of the
form
A(RIndex,CIndex)

If RIndex is a single colon, :, then RIndex is changed


(automatically) to 1:N (every row)
If CIndex is a single colon, :, then CIndex is changed
(automatically) to 1:M (every column)

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

>> logspace(A,B,N) is a 1-by-N row vector of


logarithmically spaced numbers, starting at 10A, and
ending at 10B.

Examples
>> linspace(1,4,6)
>> logspace(-1,1,5)
>> log10(logspace(-1,1,5))

37
MATLAB Math & Assignment Operators

Power ^ or .^ a^b or a.^b


Multiplication * or .* a*b or a.*b
Division / or ./ a/b or a./b
or \ or .\ b\a or b.\a
NOTE: 56/8 = 8\56

- (unary) + (unary)
Addition + a + b
Subtraction - a - b
Assignment = a = b (assign b to a)

38
Vectors and Matrices

• Vectors (arrays) are defined as


• >> v = [1, 2, 4, 5]
• >> w = [1; 2; 4; 5]

• Matrices (2D arrays) defined similarly


• >> A = [1,2,3;4,-5,6;5,-6,7]

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 =

1.200 0.500 4.00 10.00

>> 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:

x = start:end create row vector x starting with start, counting by


one, ending at end

x = start:increment:end create row vector x starting with start, counting by


increment, ending at or before end
linspace(start,end,number) create row vector x starting with start, ending at end,
having number elements
length(x) returns the length of vector x

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

the main diagonal


44
Matrices (con’t…)
• Matrix Addressing:
-- matrixname(row, column)
-- colon may be used in place of a row or column reference to select
the entire row or column.

 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

Then, the system can be described as:

Ax = b

47
Solutions to Systems of Linear Equations (con’t…)

• Solution by Matrix Inverse: • Solution by Matrix Division:


Ax = b The solution to the equation
A-1Ax = A-1b Ax = b
x = A-1b
• MATLAB: can be computed using left
>> A = [ 3 2 -1; -1 3 2; 1 -1 -1]; division.
>> b = [ 10; 5; -1];  MATLAB:
>> x = inv(A)*b >> A = [ 3 2 -1; -1 3 2; 1 -1 -1];
x= >> b = [ 10; 5; -1];
-2.0000 >> x = A\b
5.0000 x=
-6.0000 -2.0000
5.0000
-6.0000
Answer: Answer:
x1 = -2, x2 = 5, x3 = -6 x1 = -2, x2 = 5, x3 = -6
NOTE:
left division: A\b  b  A right division: x/y  x  y 48

You might also like