Attribution Non-Commercial (BY-NC)

Просмотров: 9

Attribution Non-Commercial (BY-NC)

- Tutorial MATLAB Matrix Notation
- 1st Sessional With Solution
- R reference card
- matlab_lesson_1
- 46992375 IGNOU MCA 3rd Semster Sofware Engineering Lab Record Solved MCSL 036
- Matrices - Ch. 1.6
- Matlab Triks
- Cublas Library
- 1934015040
- AS3013_lecture5
- Model-Robust Factorial Designs
- OOPs Program File
- R Language
- Arrays
- Matlab Tutorial Star MatLab
- AS3013_lecture5
- Lesson 1 R
- Computer Lab Exercise-2
- LABORATORY Manual Numerical Analysis (1)
- matlab

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Some valid variable names:

voltage valueOfR1 Ron_and_Mauro _Alan2007_

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

13

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

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

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

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

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

16

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

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

18

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

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

20

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

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

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

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

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

C or Java way:

int jenny = a[0];

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

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

26

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

How do I access elements in a matrix?

C or Java way:

int alan = a[2][3];

MATLAB way:

alan = a(3,4);

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

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:

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

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

31

sally sally sally sally = = = =

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

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

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

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

35

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

36

Example #2!

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

37

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

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

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

39

MATLAB has a really cool way of making vectors / arrays where consecutive elements are uniformly spaced Example:

Ray = 0 : 0.1 : 1.0;

Ray = [0 0.1 0.2 0.3 1.0];

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

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

Examples:

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

jenny = [0 2 4 6 8 10];

eman = [3 6 9 12 27 30];

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

3rd line: Creates an 10 element vector

ron = [1 2 3 9 10];

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

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

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

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

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

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

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

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

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

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

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

51

* is for matrix multiplication

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

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

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

54

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

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

56

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;

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

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];

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

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

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

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

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

61

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

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

63

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

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

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

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

66

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

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

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

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

70

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

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

72

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

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

74

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

75

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

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

So, youve seen how script files work

So what are function script files?

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!

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

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

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

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

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

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

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

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

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

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

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

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

87

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

88

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

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

Flow Control Basic Graphics Commands Other Useful Commands Final Words

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

91

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

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

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

Can be any row or column vector

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

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

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

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

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

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

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

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

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

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

100

Note the following:

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

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

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

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!

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

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

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

106

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

107

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

Flow Control Basic Graphics Commands Other Useful Commands Final Words

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

109

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!

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

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

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:

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

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

113

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

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

This is what Id put into the command prompt in MATLAB

You can also make a script file too if you want!

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

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

117

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

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

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

120

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 !

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

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

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

Supported colours:

blue, green, red, cyan, magenta, yellow, black

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

124

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

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

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

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

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

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

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

131

This produces a new, blank, window

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

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

133

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

Flow Control Basic Graphics Commands Other Useful Commands Final Words

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

135

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

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

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

Flow Control Basic Graphics Commands Other Useful Commands Final Words

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

139

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

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

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

- Tutorial MATLAB Matrix NotationЗагружено:georgesmaccario
- 1st Sessional With SolutionЗагружено:Tahir Iqbal
- R reference cardЗагружено:pacbard
- matlab_lesson_1Загружено:nishanthhrr
- 46992375 IGNOU MCA 3rd Semster Sofware Engineering Lab Record Solved MCSL 036Загружено:Anup Kumar Verma
- Matrices - Ch. 1.6Загружено:Bryan Penfound
- Matlab TriksЗагружено:Elie Feghali
- Cublas LibraryЗагружено:serkano77
- 1934015040Загружено:Oscar Trujillo Rodriguez
- AS3013_lecture5Загружено:Rita E. Appiah
- Model-Robust Factorial DesignsЗагружено:Jessica Li
- OOPs Program FileЗагружено:Naman Garg
- R LanguageЗагружено:cholbert
- ArraysЗагружено:Faisal Rahman
- Matlab Tutorial Star MatLabЗагружено:Paul Hernan Sany Inquilla
- AS3013_lecture5Загружено:edgar-gis
- Lesson 1 RЗагружено:VinayBale
- Computer Lab Exercise-2Загружено:dilaraatilgan
- LABORATORY Manual Numerical Analysis (1)Загружено:Hammad Fazal
- matlabЗагружено:Kamal சரவணன்
- MatLabSlides.pdfЗагружено:Danilo Pequeno
- Labview Tutorials 01Загружено:Sbo
- Fortan Arrays.pdfЗагружено:Eva Dokic
- matlab_tutorial.pdfЗагружено:Prasad Kavthakar
- laporan matlab baru.docxЗагружено:Anonymous 8cT9Hsebyt
- post reading lepЗагружено:api-378960179
- MATRICES AND DETERMINANTS final.pdfЗагружено:Lawrence Orjalesa
- wer13Загружено:Shahrukh roshan
- Matrix Algebra Calculus ReviewЗагружено:Konda Chandu
- Prelims-1Загружено:akshay

- Forecasting c 12Загружено:udhayakumar_c
- Ec 2208 Electronic Circuits Lab i l t p cЗагружено:udhayakumar_c
- Pattern Weekly&PreInternal Test QP (1)Загружено:udhayakumar_c
- SC Pre Internals1Загружено:udhayakumar_c
- Fl8 TutorialsЗагружено:Clifford Marquez
- Decision Making SyllabiЗагружено:udhayakumar_c
- PPT of Decision makingЗагружено:shiiba22
- Session 1Загружено:udhayakumar_c
- Ad-hoc 12Загружено:udhayakumar_c
- fromsdpЗагружено:udhayakumar_c
- 01-DigitalSystemsЗагружено:udhayakumar_c
- Syllabus EXTC Sem 6 NewЗагружено:udhayakumar_c

- a453 lj task newЗагружено:api-318089928
- 01 Intro to RealEyes OSMF SampleЗагружено:Samuel Shek
- Notes for Class XIIЗагружено:viplove
- Yandex Translate DgЗагружено:Yolger Perez Conde
- unix MCQЗагружено:Kishan Kumar Jha
- go_tutorial.pdfЗагружено:arunasekaran
- Ooad With Uml2.0Загружено:Vener Guevarra
- IBM Lotus Domino Integration Using IBM Tivoli Directory Integrator Redp4629Загружено:bupbechanh
- Hibernate ReferenceЗагружено:Tien D Nguyen
- Java Stored Procedures GaryRoth 22305Загружено:vijaykumar_chiniwar
- SRS-OTP.docxЗагружено:Alexandra Charles
- Pascal Tutoriala guideЗагружено:primemeridian10
- An Introduction to R for TradersЗагружено:bc500
- 9A05602 Unix InternalsЗагружено:sivabharathamurthy
- SubstitutionЗагружено:Sreekanth
- 1123-Bachelor_of_Science_(Information_Technology).pdfЗагружено:dilip yadav
- Mass Close of Purchasing DocumentsЗагружено:Abhay Deol
- Data MiningЗагружено:Smita Soma
- Airline Reservation System project Report in Asp.Net.docЗагружено:Durga Karthik
- Online Case ManagementЗагружено:Bijoy Gohain
- A Software Engineer Learns HTMLЗагружено:redmor
- C# 2012 Programming Black Book.pdfЗагружено:Dreamtech Press
- RIO_PIA_and_PeopleTools_-_Learner.pptЗагружено:Mílìnd Ràjwàrdhàn
- Excel and AutoCAD – How to link Excel with AutoCAD using VBAЗагружено:Divyadristi
- Amazon LexЗагружено:Ezhil Pandian
- COBOLЗагружено:chiru2soft
- Vb17-The ADO Set of RecordsЗагружено:kknathan3689
- oPEN SAP - Hana6 SQLЗагружено:Johanna Karina Castillo Lugo
- Programming Workshop Tutorial Sheet a, B, CЗагружено:Lincoln Foster
- Instructions-CЗагружено:api-26072581

## Гораздо больше, чем просто документы.

Откройте для себя все, что может предложить Scribd, включая книги и аудиокниги от крупных издательств.

Отменить можно в любой момент.