Вы находитесь на странице: 1из 142

ELE 532 Signals and Systems Fall 2007 MATLAB Tutorial

Raymond Phan Distributed Multimedia Computing Research (DMCR) Lab Ryerson University EPH 237 rphan@ee.ryerson.ca
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 1

http://www.ee.ryerson.ca/~rphan/ele532/MATLABTutorial.ppt

Outline of Tutorial (1)


Introduction Getting Started Variables and Starting Basics Vectors and Matrices Basic Operations Script Files Function Script Files
2

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Outline of Tutorial (2)


Flow Control Basic Graphics Commands Other Useful Commands Final Words

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Introduction (1)
So what the hell is MATLAB and whats it all about?
MATLAB: MATrix LABoratory

Created in 1970 by a dude named Cleve Moler Was (and still is) used extensively at Stanford University and the University of New Mexico
Why? To make calculating the following things a lot easier!
Matrix Theory Linear Algebra Numerical Analysis
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 4

Introduction (2)
MATLAB is selected as a numerical analysis tool over languages like C and Java because:
Very EASY programming language Powerful graphics capabilities Very sleek and interactive interface Great for general scientific and engineering computation

Later in your courses, youre going to start to use this heavily, especially in:
ELE 639: Control Systems ELE 792: Digital Signal Processing any signal processing and controls course in 4th year
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 5

Outline of Tutorial (1)


Introduction Getting Started Variables and Starting Basics Vectors and Matrices Basic Operations Script Files Function Script Files
6

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Getting Started (1)


Where can I find and use MATLAB? Method #1: On the EE undergraduate network labs:
ENG 406, 407, 408 and 409
Log onto an EE undergraduate terminal A) Go to Applications Accessories Terminal and type in matlab (without the quotes) B) Go to Applications Math MATLAB 2007a

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Getting Started (2)


Method #2: If you dont feel like using the computers at school, you can install your own copy of MATLAB on your PC or laptop
There are many ways to obtain your own copy:
Buy a student version at the Ryerson Bookstore Obtain a trial version online via: http://www.mathworks.com Borrow from a friend

Version of MATLAB needed for these labs: MATLAB 7.0 and up NOTE!: You MUST have the Java Runtime Environment (JRE) installed on your system
At LEAST 5.0 and up

MATLAB uses the JRE as a backbone to run the whole application


ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 8

What happens next!?

Getting Started (3)

MATLAB Interface: >> means its ready for input from you

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Outline of Tutorial (1)


Introduction Getting Started Variables and Starting Basics Vectors and Matrices Basic Operations Script Files Function Script Files
10

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Variables and Basic Commands (1)


One GREAT thing about MATLAB:
MATLAB is a programming language that is dynamically typed what does this mean? You can declare variables and initialize them without specifying what type they are
MATLAB automatically figures this out for you, or you can choose to manually override the type

Example:
C or Java way: int nikhil = 1, double jenny = 2 MATLAB way: nikhil = 1, jenny = 2
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 11

Variables and Basic Commands (2)


When you want to assign something to a variable, use the = sign When you assign something to a variable, MATLAB initializes & automatically declares it Guidelines for variable names:
All must be single words, no spaces Must begin with a letter, numbers or the underscore character ( _ ) Variable names are case sensitive
i.e nikhil is NOT the same as Nikhil i.e muffin is NOT the same as mUFfin

Names can be up to 19 characters in length


ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 12

Variables and Basic Commands (3)


Some valid variable names:
voltage valueOfR1 Ron_and_Mauro _Alan2007_

Some invalid variable names (why are these invalid?):


123 value of R1 3v X#*()$#$!!!
13

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Variables and Basic Commands (4)


Left panel: Current Directory / Workspace
A) Shows you directory structure to access working directory (more on this later) B) Shows you all of the variables that have been created and can be accessed

Right: Command Prompt


Enter commands and variable declarations here Commands without a semicolon ( ; ) echo your command to screen Commands with a semicolon suppress that output
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 14

Can enter commands either:

Variables and Basic Commands (5)


One at a time: The end of each command, press ENTER (carriage return) Multiple commands in one line:
Suppress echoing: Use semicolons to separate each command on the line Enable echoing: Use commas ( , ) to separate each command on the line

Typing in a variable by itself and pressing ENTER will redisplay the variable Entering a value, pressing ENTER, and not assigning it to anything, the value will be automatically assigned to a variable called ans (answer)
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 15

Variables and Basic Commands (6)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

16

Variables and Basic Commands (7)


who command: Shows you all of the variables created by you
You can also check the workspace as well

clear command: Clears all of the variables shown in the workspace, and you start from scratch clc command: Flushes the command prompt
Variables will still be in the workspace, but it clears the command prompt screen
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 17

Variables and Basic Commands (8)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

18

Variables and Basic Commands (9)


Can also declare complex numbers too:
Can add, subtract, multiply and divide

You can use i or j to declare complex numbers Of course you can also add, subtract, multiply and divide normal numbers too!
Too lazy to make a slide for it However, well get into addition, subtraction, multiplication and division in another way later
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 19

Variables and Basic Commands (10)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

20

Variables and Basic Commands (11)


Command History window: Used to keep track of the commands you ran recently
You can also double click on any of the commands to re-run them again You can also press the up & down keys to cycle through the commands as well in the command prompt
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 21

Outline of Tutorial (1)


Introduction Getting Started Variables and Starting Basics Vectors and Matrices Basic Operations Script Files Function Script Files
22

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Vectors and Matrices (1)


Unless otherwise defined, MATLAB treats ALL variables as 2D matrices how is this possible?
Arrays and Vectors: N x 1 or 1 x N matrix Single value: 1 x 1 matrix

Why does MATLAB decide to handle it this way?


Youll see later that handling variables as matrices makes things A LOT faster and easier to work with
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 23

Vectors and Matrices (2)


How do you declare a vector / array in MATLAB?
C or Java way: int a[4] = {1, 2, 3, 4}; MATLAB way:
a = [1 2 3 4] row vector
Spaces mean to move to the next column

a = [1 2 3 4]. (. operator means to transpose a vector) - column vector a = [1;2;3;4] - column vector
Semicolon means to move to the next row

You do not have to specify how big the vector is first before you make it
Beauty of dynamically typed languages! MATLAB automatically figures out how big it is and you go from there
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 24

How do I access elements in a vector / array?


C or Java way:
int jenny = a[0];

Vectors and Matrices (3)

MATLAB way:
jenny = a(1);

NOTE!:
No square brackets when accessing an element! Use round brackets! Elements do not start at index 0, they start at index 1!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 25

Vector and Matrices (4)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

26

Vector and Matrices (5)


How do I create a matrix in MATLAB?
C or Java way: int a[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; MATLAB way:
#1: a = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]; #2: a = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16];
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 27

Vector and Matrices (6)


How do I access elements in a matrix?
C or Java way:
int alan = a[2][3];

MATLAB way:
alan = a(3,4);

Whats the difference here?


No separate brackets for each dimension Comma is used to separate the dimensions All indices to access arrays are offset by 1! Remember: 1st parameter is the row, 2nd parameter is the column
28

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Vector and Matrices (7)


Heres something to mess you up how do I access a range of values in a matrix? Suppose I had a matrix already created called ray
How do I get all of the elements in the 1st row?
C or Java way:
int i; for(i = 0; i < 4; i++) ray[i] = a[0][i]; This is a pain in the butt!... Theres gotta be an easier way to do this!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 29

MATLAB way:

Vectors and Matrices (8)

ray = a(1, 1:4); ray = a(1, :);

Whats the difference here?!


NO for loop! The colon ( : ) operator is used to access a range of values
There is a more general use for this, but well get into this later

1 : 4 means a range from 1 through 4 for a dimension : by itself means give me all possible values in a dimension Doing 1 : 4 in the 2nd parameter means give me columns 1 through 4 Doing : in the 2nd parameter means give me all of the columns!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 30

Vectors and Matrices (9)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

31

Some more examples:


sally sally sally sally = = = =

Vectors and Matrices (10)


a(2,3); a(1:3,3:4); a(:, 1:3); a(2:4,:);

1st line: Access 2nd row, 3rd column element, and assign it to sally 2nd line: Get a matrix with elements between rows 1 3, and columns 3 4 and assign this to sally 3rd line: Get a matrix with elements between columns 1 3 and give me every possible row, and assign this to sally 4th line: Get a matrix with elements between rows 2 4 and give me every possible column, and assign this to sally
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 32

Vectors and Matrices (11)


Heres a curve ball!
Joe = a(:,:); Joe = a;

What does this mean? Copy the entire matrix, a, and assign it to Joe You can also do the 2nd line too. Its exactly the same meaning
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 33

Vectors and Matrices (12)


Example Time!

1) How do we define M in MATLAB syntax? 2) How do we execute a), b), c) and d)?
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 34

Vectors and Matrices (13)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

35

Vectors and Matrices (14)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

36

Vectors and Matrices (15)


Example #2!

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

37

Vectors and Matrices (16)


In other words, with matrices A, B and C, make me a matrix that looks like this!

What do we need to do?


How do we define matrices A, B and C? How do we create M?
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 38

Vectors and Matrices (17)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

39

Vectors and Matrices (18)


MATLAB has a really cool way of making vectors / arrays where consecutive elements are uniformly spaced Example:
Ray = 0 : 0.1 : 1.0;

This generates a vector / array with 11 elements, such that


Ray = [0 0.1 0.2 0.3 1.0];
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 40

Vectors and Matrices (19)


General Form:
new_array = first_value : increment : last_value Make note of the colons ( : )!

first_value: The first value in the new vector / array last_value: The last value in the new vector / array increment: The step size
If you dont include this value, it is automatically assumed to be 1
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 41

Vectors and Matrices (20)


Examples:
jenny = 0 : 2 : 10; eman = 3 : 3 : 30; ron = 1 : 10; mauro = 2.0 : -0.2 : 0.4;

1st line: Creates a 6 element vector


jenny = [0 2 4 6 8 10];

2nd line: Creates a 10 element vector


eman = [3 6 9 12 27 30];
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 42

Vectors and Matrices (22)


3rd line: Creates an 10 element vector
ron = [1 2 3 9 10];

4th line: Creates a 8 element vector


mauro = [2.0 1.8 0.6 0.4];

Pretty easy dont you think!? Remember how I told you about that colon operator?... Well, here you go! To do this in C and Java, it requires a bit more work.
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 43

Vectors and Matrices (23)


Some useful matrix and vector / array commands
eye(n): Creates an n x n identity matrix

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

44

Vectors and Matrices (24)


Some useful matrix and vector / array commands
ones(n,m): Creates an n x m matrix full of ones

ones(1,n) or ones(n,1): Creates an array / vector that has n elements, full of ones
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 45

Vectors and Matrices (25)


Some useful matrix and vector / array commands
zeros(n,m): Creates an n x m matrix full of zeros

zeros(1,n) or zeros(n,1): Creates an array / vector that has n elements, full of zeros
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 46

Vectors and Matrices (26)


Last important note:
MATLAB evaluates expressions to the right of the equals sign first After, it assigns this result to the variable to the left of the equals sign Heres an example: sum = 2; sum = sum + 3; What happens here? sum gets assigned the value of 2 first, then it gets added with 3, and stored back into sum

and thats it for this section whew!


ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 47

Outline of Tutorial (1)


Introduction Getting Started Variables and Starting Basics Vectors and Matrices Basic Operations Script Files Function Script Files
48

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Basic Operations (1)


Lets assume the following:
A and B: Are matrices or vectors / arrays of compatible dimensions
Assume they can be added, subtracted, multiplied and divided properly

n is a scalar (single value number)

Heres a table that provides a good summary of all of the basic operations you can perform on matrices and vectors / arrays
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 49

Basic Operations (2)

Here, the elements in the matrices or vectors / arrays can be real or complex Addition and Subtraction will just add and subtract two matrices normally For vectors, each corresponding component gets added or subtracted
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 50

Basic Operations (3)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

51

Basic Operations (4)

Multiplication (this kind) only works for matrices


* is for matrix multiplication

Division is a little bit more complicated


We have left division and right division
Left Division == A-1B Right Division == AB-1
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 52

Basic Operations (5)

Transposition: Transposes a matrix or vector


operator
Real valued entries: Normal Transpose Complex valued entries: Tranposes and performs complex conjugate

. operator
Real and Complex valued entries: Normal Transpose
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 53

Basic Operations (6)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

54

Basic Operations (7)


Exponentiation multiplies a matrix with itself n times For calculations with *, /, \, and ^, there is something called element-by-element operations for vectors / arrays and matrices
You put a dot operator ( . ) before the operation
Example: .* or ./ or .\ or .^

The 1st element of A is *, /, \ or ^ with the 1st element of B, and that result gets stored dont get it? Heres an example
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 55

Basic Operations (8)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

56

Basic Operations (9)


Special Case:
If you wanted to multiply or divide every number in a matrix or vector / array by a constant, you can just simply do the following: Example: t = 0 : 2 : 20; t = [0 2 4 18 20]; g = 2*t; g = [0 4 8 36 40]; or g = 2.*t; h = t/4; h = [0 0.5 1 4.5 5]; or h = t./4;

All you have to do is multiply or divide by the desired number


No need to create another matrix or vector / array and do point-bypoint multiplication or division!
57

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Basic Operations (10)


Special Case #2:
If you wanted to add or subtract every number in a matrix or vector / array by a constant, you can just simply do the following: Example: t = 0 : 20; t = [0 2 4 18 20];

g = t + 2; g = [2 4 6 20 22];
h = t - 4; h = [-2 0 2 16 18];

All you have to do is add or subtract by the desired number


No need to create another matrix or vector / array and add or subtract that way!

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

58

Basic Operations (10)


Here are some useful commands for matrices and vectors / arrays: Assume that V is a vector of arbitrary length and M is a matrix of arbitrary size len = length(V);
Gives the number of elements the vector V has, and stores it into len

[rows cols] = size(M);


Gives the number of rows and columns and stores them into rows and cols respectively Dont worry about the square braces for now, well deal with them later.
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 59

Basic Operations (11)


sum(V): Returns the sum of all elements contained in vector V sum(M): Returns a row vector, where each element is the sum of the columns of matrix M confused? Dont worry, check out this example

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

60

Basic Operations (12)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

61

Basic Operations (13)


prod(V): Returns the product of all elements contained in vector V
We multiply every single element in the vector with each other

prod(M): Returns a row vector, where each element is the product of the columns of matrix M confused? Dont worry, check out this example
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 62

Basic Operations (14)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

63

Basic Operations (15)


Quick quiz:
Suppose I perform this operation:
V = n : -1 : 1;
n can be any number > 0

sum = prod(V);

What is the above operation equivalently called in mathematics? youve seen this before. Think MTH 314

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

64

Basic Operations (16)


Its a factorial! Anyway, lets keep going max(V) / min(V): Returns the maximum / minimum of all elements contained in vector V max(M) / min(M): Returns a row vector, where each element is the maximum / minimum of the columns of matrix M

confused again? No worries, heres another example


ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 65

Basic Operations (17)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

66

Outline of Tutorial (1)


Introduction Getting Started Variables and Starting Basics Vectors and Matrices Basic Operations Script Files Function Script Files
67

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Script Files (1)


So far, youve seen that MATLAB can accept and execute commands interactively through the command prompt
what happens if youve got A LOT of commands to execute?

Think C or Java: You put all commands or syntax into a file and execute that file. You can do this with MATLAB, and you dont have to input all of the commands individually.
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 68

Script Files (2)


This kind of file is called a script file or M-file (M for MATLAB!)
You place all commands you want to execute in a file with extension .m at the end, and you run the script file MATLAB will run all of these commands in sequence for you

To execute a script file, make sure you set the working directory to be where the script file is located (remember I said wed get back to this earlier?)
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 69

Script Files (3)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

70

Script Files (4)


MATLAB has a M-file editor that you can use where you can create your scripts
You can also use any other word processing editor. Just make sure the extension of the file is .m Its got:
Some nice colour coding features Debugging Tools Interoperability with the MATLAB command prompt
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 71

Script Files (5)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

72

Script Files (6)


Once a script file has been created, type in the name of the file (without the .m) in the command prompt to execute the script
Make sure you set the proper working directory!

When you execute a script file, all of the variables created in the script file get stored in the workspace for future use Lets do an example:
Lets make the factorial example into a script file
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 73

Script Files (7)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

74

Script Files (8)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

75

Script Files (9)


The great thing about script files is that commands can be re-executed without having to enter them all again!
All you have to do is modify parts of the script file to give you the result you want

The script file is now set to compute 4! What if I wanted to do 9!, or 12!, or 5! ?
Just change the n parameter accordingly
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 76

Outline of Tutorial (1)


Introduction Getting Started Variables and Starting Basics Vectors and Matrices Basic Operations Script Files Function Script Files
77

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Function Script Files (1)


So, youve seen how script files work
So what are function script files?

Think Java: These are methods


You send input variables into a function
Difference: You dont have to define what the variable types are. Remember: Dynamically Typed!

The function performs MATLAB commands with these input variables The function returns output variables
Difference: You can return more than one variable! You dont have to define the variable type either!

Unlike C or Java, you do not require return statements to return variables


All you have to do is assign something to the variable, and thats it.
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 78

Function Script Files (2)


Why would you want function script files?
Instead of changing some parts of a script file, you can do these changes by providing different variables to the input of the function There may be a case where when you run a script, you dont want variables created in the script to be saved to the workspace

Function scripts only communicate with the MATLAB workspace with:


The variables that you pass to it The variables that get sent to the output after its finished
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 79

Function Script Files (3)


What does this mean?
Any variables you create within the function will be discarded after the function has finished executing This is what we call local scope

How do we create a function script file?


Pretty much the same as a normal script file
.m as the extension to the file

Remember, with a script file, all you had to do was enter in the commands in sequence
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 80

Function Script Files (4)


However, there are two differences between a script file, and a function script file
The file name of the function has to be the same as the function itself The first line of a function script file must be the following: function [output1, output2,] = function_name(input1, input2, )
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 81

Function Script Files (5)


The function keyword means that this script file is a function script file input1, input2, represents the input variables going into the function output1, output2, represents the output variables going into the function You may have noticed that there are square braces ( [ ] ) surrounding the output variables in the function header
In order to return more than one variable, MATLAB puts all of the variables into one vector and returns this vector, hence the [ ] smart eh?
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 82

Function Script Files (6)


Use the % operator to put in comments
If you want to perform the modulus, use the mod function mod(x,y) == x % y in C or Java

If you want to comment out a block of code, do the following: %{ commands that are commented out %} When youre coding a function script file, its a good idea to put an authors block at the beginning of the file, that tells someone how the function works, what inputs you need, what outputs come out, and how to use it
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 83

Some examples of function script files that you have seen already:
eye(n)
Input: number n, n > 0 Output: n x n identity matrix

Function Script Files (7)

prod(V), prod(M)
Input: Vector V or Matrix M Output: A number or a vector

sum(V), sum(M)
Input: Vector V or Matrix M Output: A number or a vector

max(V), max(M)
Input: Vector V or Matrix M Output: A number or a vector

min(V), min(M)
Input: Vector V or Matrix M Output: A number or a vector
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 84

Function Script Files (8)


Heres another one that you saw earlier:
[rows cols] = size(M)
Input: Matrix M Output: 2 numbers, the rows and columns of the matrix

When you call this function script file in MATLAB, make sure the square braces are there This is required if the function script file returns more than 1 variable Failing to do this will result in the very last output variable to be saved instead
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 85

Function Script Files (9)


So now with this, lets go back to our factorial example and make this a function script file What do we need to do in order to make this a function script file?
Think back to the two differences that I said earlier about script files and function script files
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 86

Function Script Files (10)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

87

Function Script Files (11)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

88

Function Script Files (12)


Some important things to be reminded of:
n in the function script file is not saved to the workspace
n has a local scope!

Instead of changing the parameter n, as we did in a script file, we simply changed the input parameter of the function If your function returns more than one variable, make sure you save them to a vector!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 89

Outline of Tutorial (1)


Introduction Getting Started Variables and Starting Basics Vectors and Matrices Basic Operations Script Files Function Script Files
90

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Outline of Tutorial (2)


Flow Control Basic Graphics Commands Other Useful Commands Final Words

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

91

Flow Control (1)


Youve seen this in C or Java many times Flow control allows your script or function script file to have decision making abilities understand what I mean? If you dont, MATLAB supports the following common flow control methods
for loop while loop if-else & else-if statements switch-case-otherwise statements

now you see what I mean right?


ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 92

Flow Control (2)


for loops allow a group of commands to be executed a predetermined amount of times This loop has the following structure:
for i = any_array commands to be executed end

any_array is any valid array


Can be any row or column vector
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 93

Flow Control (3)


How this for loop works is as follows:
1st iteration, i = any_array(1), then execute commands 2nd iteration, i = any_array(2), then execute commands nth iteration, i = any_array(n), then execute commands

This can prove to be a very powerful mechanism


Your for loop indices never have to be in uniform steps!

Dont know what I mean?... Lets do an example


ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 94

Flow Control (4)


First Example: for loop in uniform steps
f = 1; for i = 1:n f = f*i; end Here, were computing our factorial function, but with the use of a for loop

i is assigned 1 for the 1st iteration, 2 for the 2nd iteration, and n for the nth iteration For each iteration, we take the previous value of f and multiply by the current value of i
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 95

Flow Control (5)


Second Example: for loop in non-uniform steps
val = 0; array = 1 : 20; for i = [1 4 8 9 10 2 5] val = val + array(i); end Here, were computing the sum of random elements in an array and storing them into val

Take a close look at what I did in the for loop The 1st iteration, i = 1, the 2nd iteration, i = 4, the 3rd iteration, i = 8, and so on Pretty cool eh!? You dont have to have uniform steps in your for loops!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 96

Flow Control (6)


while loops let you execute a group of commands indefinitely until a condition is met The structure for this loop is as follows:
while expression commands to be executed end
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 97

Flow Control (7)


The commands between the while and the end statements are executed until expression is evaluated as false, or a zero (0) value You usually use relational or equality operators in the expression statement of the while loop A relational or equality expression is assigned a value of 1 if its true, and 0 if its false
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 98

Flow Control (8)

Everything here is the same as C and Java, except for the not equals to operator. MATLAB has it as ~=, and C or Java has it as != be careful not to mix these up!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 99

Flow Control (9)


if-else & else-if statements help you execute blocks of commands when some condition is true Heres the syntax for it but Im sure you already know this
if exp_1 commands to be elseif exp_2 commands to be elseif exp_3 commands to be else commands to be end
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

executed if exp_1 is true

executed if exp_2 is true

executed if exp_3 is true

executed if none of the above is true

100

Flow Control (10)


Note the following:
elseif and else operators are optional You can have if statements by themselves as well without the above operators

The break command:


Used often in for and while loops When this command is encountered, the loop stops executing immediately and carries onto the next block of code If youre using this within nested loops, the inner most loop stops executing only
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 101

Flow Control (11)


switch-case-otherwise statements are a special case (no pun intended) of the if-else & else-if statements You choose between a finite number of choices; each choice consists of a block of commands to be executed If the choice you make is none of the choices provided in this statement, we execute a default (otherwise) code block so this is what this kind of statement looks like:
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 102

Flow Control (12)


switch expr case value1, commands to be executed if expr equals value1 case value2, commands to be executed if expr equals value2 otherwise, commands to be executed if the value of expr is not equal to any of the above values end You usually use switch statements when you want your program to run differently, based on the input parameters that are given to your function script file
103

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

Lets do an example!

Flow Control (13)

Lets use the while and if-else statements to


make a simple program You all have studied logic gates in COE 328, so lets use some simple facts from this Lets make a program that will classify a set of input voltages according to the following specs:
If Vout is between 0V and 0.5V, this is a logic 0 (0) If Vout is between 2.7V and 5V, this is a logic 1 (1) All other voltages are classified as invalid (-1)

The program will read in an array of continuous input voltages, and output an array of the same size Each element will take 1 of 3 possible values: 0, 1 and -1
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 104

Flow Control (14)


What do I need to do?
Set up a function script file with the function keyword, and the appropriate inputs and outputs
Lets call this function: classify_TTL Inputs: V, an array of continuous input voltages Outputs: logic_levels, an classification array telling you whether you have logic 0, logic 1, or invalid voltages

Naturally, you want to use a for or while loop for this program because you want to check through every element in this input array You use an if-else statement to check to see what the voltage inputs are, then you classify accordingly
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 105

Flow Control (15)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

106

Flow Control (16)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

107

Flow Control (17)

Above, I declared an array of 7 input voltages and ran the function The 2nd element is valid as logic 0 because its between 0V and 0.5V The 5th and 6th element is valid as logic 1 because theyre between 2.7V and 5V The rest are invalid
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 108

Outline of Tutorial (2)


Flow Control Basic Graphics Commands Other Useful Commands Final Words

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

109

Basic Graphics Commands (1)


MATLAB provides a variety of sophisticated techniques for presenting and visualizing data Also, MATLAB makes it very easy to plot data!
I have never used MS Excel ever again because MATLAB makes it easy!

The watered down version:


Provide an array of values for each set of axes Run a function that plots things for you Run a few more commands that will make a grid, set the title of the graph, the title of the axes and so on
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 110

Basic Graphics Commands (2)


2D plotting: MATLAB makes this very easy!
If x and y are arrays of elements that are the same size, you can plot them using this data with the following command: plot(x, y); This will bring up a window plotting a graph of y vs. x To plot something simple, thats just about it!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 111

Basic Graphics Commands (3)


Heres a basic example if you dont believe me Lets say I wanted to plot the line y = x Lets choose 101 points between 0 to 10 in steps of 0.1 Heres the syntax Id use:

and thats it! This is what the graph looks like


ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 112

Basic Graphics Commands (4)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

113

Basic Graphics Commands (5)


If you want to plot multiple plots on a single graph, you do the following: plot(x1,y1,x2,y2,,xN,yN); N is the number of plots you want to appear on the single graph xi and yi are the points to the ith graph you want plotted on the single graph The number of elements between (x1,y1), (x2,y2), (xN,yN) must all be the same!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 114

Basic Graphics Commands (6)


Lets do another example:
Lets plot the following 5 lines: y1 = 0.1x y2 = 0.5x y3 = 2x y4 = 5x y5 = 10x
For now, lets make them all go from 0 to 10 in step sizes of 0.1 These plots dont all have to have the same step size!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 115

Basic Graphics Commands (7)


This is what Id put into the command prompt in MATLAB
You can also make a script file too if you want!

and this is what the graph looks like!


ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 116

Basic Graphics Commands (8)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

117

Basic Graphics Commands (9)


MATLAB automatically colour codes the different plots that are on the graph This graph looks pretty plain theres gotta be more that you can add, and yes you can You can add a title, label the axes, put a grid on and even a legend!
You can add these in the graph GUI that youve just seen, or do it through the command prompt
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 118

Basic Graphics Commands (10)


So lets say I wanted to add a title, add a grid, label the axes and put up a legend, how would I do that?

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

119

Basic Graphics Commands (11)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

120

Basic Graphics Commands (12)


grid puts a grid on the graph
The spacing for the grid is automatically figured out by MATLAB

title() lets your graph have a title xlabel(), ylabel() labels the x and y axes accordingly
Put the labels inside the quotations Dont forget the quotations !

legend(, , , ) produces a legend, labeling what each plot is on the graph


ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 121

Basic Graphics Commands (13)


Remember, for the legend command, you label the plots the same order as how you plotted them! By default, MATLAB takes all points and connects them with a solid line, and its got its own way of determining which colour belongs to what plot Is there a way to control this?... Yes there is!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 122

Basic Graphics Commands (14)


In addition to the x and y points, you specify an additional parameter: plot(x, y, line_style); line_style is a character string of 2 characters
The 1st character specifies the colour of your plot The 2nd character specifies how your plot will be plotted on the graph, or the plot style
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 123

Basic Graphics Commands (15)


Supported colours:
blue, green, red, cyan, magenta, yellow, black

Supported plot styles:

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

124

Basic Graphics Commands (16)


Examples: x = 0:0.1:10; y = x;
plot(x,y,g.);
This will plot a green line with dots at each point

plot(x,y,bo);
This will plot a blue line with circles at each point

plot(x,y,'rx);
This will plot a red line with crosses at each point
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 125

Basic Graphics Commands (17)


Like how we saw before, you can put multiple plots on a single graph, each with their own colour and plot styles with the following: plot(x1, y1, line_style1, x2, y2, line_style2,..., xN, yN, line_styleN); N is the number of plots you want to appear on the single graph xi and yi are the points to the ith graph you want plotted on the single graph line_stylei is the plot style and colour of that ith graph The number of elements between (x1,y1), (x2,y2), (xN,yN) must all be the same!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 126

Basic Graphics Commands (18)


There is also a way to produce multiple graphs in one window
You can have more than 1 graph in one window at a time!

You do this by using the subplot command The subplot command treats the window as if it had multiple slots
Each slot takes in a graph
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 127

Basic Graphics Commands (19)


How do we use the subplot command?
subplot(m,n,p) or subplot(mnp) m and n you need to know before hand
These determine the number of rows (m) and columns (n) for the amount of graphs you want p determines which location in the window you want the plot to go to The order is from left to right, top to bottom

In order to properly use subplot, you must call this function first After, you code the syntax to plot something normally
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 128

Basic Graphics Commands (20)


Heres a small example:
If I wanted to make a window that has 4 plots, 2 plots in each row 2 rows, heres what Id do
Do subplot(221) Specify that we want to work on the top left corner Next, code the syntax to plot normally. The plot will appear on the top left corner Do subplot(222) Specify that we want to work on the top right corner Next, code the syntax to plot normally. The plot will appear on the top right corner Do subplot(223) Specify that we want to work on the bottom left corner Next, code the syntax to plot normally. The plot will appear on the bottom left corner Do subplot(224) Specify that we want to work on the bottom right corner Next, code the syntax to plot normally. The plot will appear on the bottom right corner
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 129

Basic Graphics Commands (21)


Lets do another example in case you didnt get what I meant earlier Lets make 4 graphs, have 2 rows and 2 columns for the window. Each graph will have one plot.
Lets make each plot the following: 1. y1 = sin(x); 2. y2 = cos(x); 3. y3 = 3x; 4. y4 = 6x; Lets make the range of the plot go from: x = -10 : 0.1 : 10; now what?
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 130

Basic Graphics Commands (22)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

131

1st step Use the figure command


This produces a new, blank, window

Basic Graphics Commands (23)

Use the subplot command to specify the number of rows and columns and which plot you want to draw first
Number ordering convention Left to right, top to bottom

Code the normal syntax you need to produce a plot. Use the plot command when youre done Use the subplot command again to go to the next area, and code the plot syntax again Repeat until youre done and heres what the window looks like!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 132

Basic Graphics Commands (24)

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

133

Basic Graphics Commands (25)


Some functions, like cos and sin take in, not only single values, but vectors / arrays and matrices cos and sin apply their respective mathematical operations to every element if the input is a vector / array, or matrix The output will be a vector / array, or matrix, of the same size, with the function applied to each element in that memory chunk
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 134

Outline of Tutorial (2)


Flow Control Basic Graphics Commands Other Useful Commands Final Words

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

135

Other Useful Commands (1)


MATLAB has a great help facility, both through its interface and online If you need help regarding how a certain command works, type in the following in the command prompt:
help command

command is the command you want to look up and to see how it works
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 136

Other Useful Commands (2)


If you dont know what a particular function is called, you can use the lookfor command Its called the following way:
lookfor command

Where command is the function youre looking for MATLAB searches all of its libraries that are related to command
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 137

Other Useful Commands (3)


A list of all of the MATLAB commands you have invoked in a session in the command prompt can be written into a file with the diary command You call this command this way in the command prompt diary diary_file diary_file is the name of the file where your commands you invoked in that session will be stored If the file already exists, your commands in the current session will be appended to the file Use diary off to turn off the diary command, and diary on to reactivate it
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 138

Outline of Tutorial (2)


Flow Control Basic Graphics Commands Other Useful Commands Final Words

ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007

139

Final Words (1)


This tutorial provided you the basics of how to use MATLAB and enough to get you started with these labs This tutorial, however, is not exhaustive
There are still a lot of commands out there that perform really cool stuff for you Consider taking some time to look at them and see how cool MATLAB is

Always use the help and lookfor commands when youre learning a new function If all else fails, ask me!
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 140

Final Words (2)


I adapted this tutorial from Dr. Y. C. Chens Introduction to MATLAB tutorial and can be found here:
http://www.ee.ryerson.ca/~rphan/matlabtutorial.pdf

I also wrote a tutorial for the Ryerson IEEE Student Branch website 3 years ago, and can be found here:
http://www.ee.ryerson.ca/~ieee/articles/MATLAB.html
ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 141

Thanks For Listening! Any Questions?


ELE 532 Signals and Systems MATLAB Tutorial Friday, September 14th, 2007 142

Вам также может понравиться