Anda di halaman 1dari 45

ELG 3125 - Lab 1

Introduction to MATLAB
TA: Chao Wang
2008 Fall (cwang103@site.uOttawa.ca)

ELG 3125 Signal and System Analysis

P. 1

Do You Speak MATLAB?


MATLAB - The Language of Technical Computing

ELG 3125 Signal and System Analysis

P. 2

Whats MATLAB ?
MATLAB is a program for doing numerical computation. It was originally designed for solving linear algebra type problems using matrices. Its name is derived from MATrix LABoratory. MATLAB has since been expanded and now has built-in functions for solving problems requiring data analysis, signal processing, optimization, and several other types of scientific computations. It also contains functions for 2-D and 3-D graphics and animation. (Toolboxes)
ELG 3125 Signal and System Analysis
P. 3

Starting MATLAB
When starting up the MATLAB program, MATLAB loads and checks that a license is available and throws up a splash screen.

ELG 3125 Signal and System Analysis

P. 4

Starting MATLAB
Next MATLABs desktop appears.
Command Window Current Directory Workspace Browser Command History Launch Pad

ELG 3125 Signal and System Analysis

P. 5

MATLAB Desktop
Command Window
The MATLAB environment is command oriented somewhat like UNIX or DOS. A prompt appears on the screen and a MATLAB statement can be entered. Use the Command window to enter variables and run functions and M-files. When the <ENTER> key is pressed, the statement is executed, and another prompt appears.
ELG 3125 Signal and System Analysis
P. 6

MATLAB Desktop
Command Window (cont.)
If a statement is terminated with a semicolon ( ; ), no results will be displayed. Otherwise results will appear before the next prompt. Right is an example from a MATLAB screen.

ELG 3125 Signal and System Analysis

P. 7

MATLAB Desktop
Command History
Statements you enter in the Command window are logged in the Command Histroy. Simply double-click the command.

ELG 3125 Signal and System Analysis

P. 8

MATLAB Desktop
Workspace Browser
Consists of the set of all current variables built up during a MATLAB session and stored in memory. Add variables to the workspace by using functions, running M-files and loading saved workspaces.

ELG 3125 Signal and System Analysis

P. 9

MATLAB Desktop
Workspace Browser (cont.)
Commands for workspace variables: who, whos current variables in workspace save save workspace variables to *.mat file load load variables from .mat file clear, clear all clear workspace variables

ELG 3125 Signal and System Analysis

P. 10

MATLAB Desktop
Current Directory
File and folder information in the current directory

ELG 3125 Signal and System Analysis

P. 11

MATLAB Desktop
Launch Pad
access tools, demos

and documentation

ELG 3125 Signal and System Analysis

P. 12

MATLAB Variables
Variable names
Variable names ARE case sensitive

Variable names can contain up to 63 characters (as of MATLAB 6.5 and newer) Variable names MUST start with a letter followed by letters, digits, and underscores. (for example: x, y, my_var, Y_2, time_2_frequency)

ELG 3125 Signal and System Analysis

P. 13

MATLAB Variables
MATLAB special variables
ans pi eps inf NaN i and j realmin realmax Default variable name for results Value of Smallest incremental number Infinity Not a number e.g. 0/0 i = j = square root of -1 The smallest usable positive real number The largest usable positive real number

ELG 3125 Signal and System Analysis

P. 14

MATLAB Symbols
Some MATLAB symbols
>> ... , % ; : prompt continue statement on next line separate statements and data start comment which ends at end of line (1) suppress output (2) used as a row separator in a matrix specify range

ELG 3125 Signal and System Analysis

P. 15

MATLAB Matrices
MATLAB treats all variables as matrices. For our purposes a matrix can be thought of as an array, in fact, that is how it is stored. Vectors are special forms of matrices and contain only one row OR one column. Scalars are matrices with only one row AND one column

ELG 3125 Signal and System Analysis

P. 16

MATLAB Matrices
A matrix with only one row AND one column is a scalar. A scalar can be created in MATLAB as follows:

ELG 3125 Signal and System Analysis

P. 17

MATLAB Matrices
A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas):

ELG 3125 Signal and System Analysis

P. 18

MATLAB Matrices
A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows (note the semicolons):

ELG 3125 Signal and System Analysis

P. 19

MATLAB Matrices
A matrix can be created in MATLAB as 2-D form (note the commas AND semicolons):

ELG 3125 Signal and System Analysis

P. 20

MATLAB Matrices
Matrix Operations
transpose: subscription:

ELG 3125 Signal and System Analysis

P. 21

MATLAB Matrices
Matrix Operations (cont.)
whole row: whole column:

ELG 3125 Signal and System Analysis

P. 22

MATLAB Matrices
Extracting a Sub-Matrix
A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names of both matrices and the rows and columns to extract. The syntax is: sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ; where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and ending columns to be extracted to make the new matrix.

ELG 3125 Signal and System Analysis

P. 23

MATLAB Matrices
Extracting a Sub-Matrix (cont.)

ELG 3125 Signal and System Analysis

P. 24

MATLAB Matrices
Generating Matrix from built-in Functions
zeros(M,N) MxN matrix of zeros ones(M,N) MxN matrix of ones rand(M,N)
MxN matrix of uniformly distributed random numbers on (0,1)

ELG 3125 Signal and System Analysis

P. 25

MATLAB Operators
Arithmetic Operators
+ * / \ ^ unary addition unary subtraction multiplication right division left division (56/8=8\56) power complex conjugate transpose .* ./ .^ . element-by-element mult. element-by-element div element-by-element power transpose

ELG 3125 Signal and System Analysis

P. 26

MATLAB Operators
Relational and Logical Operators
== ~= < <= > >= equal not equal less than less than or equal greater than greater than or equal
& | ~ AND OR NOT

ELG 3125 Signal and System Analysis

P. 27

MATLAB Flow Control


MATLAB has six basic flow control constructs:
if-elseif-else statements switch-case statements for loops while loops break statements: Terminate execution of WHILE or FOR loop. - continue statements: Pass control to the next iteration of FOR or WHILE loop.

ELG 3125 Signal and System Analysis

P. 28

MATLAB M-Files
Sequences of MATLAB commands can be written to files with the extension *.m, called M-files. Entering the name of the file (without the extension) causes automatic execution of all the statements in the file.

ELG 3125 Signal and System Analysis

P. 29

MATLAB M-Files
There are two kinds of M-files
- Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace. (Simplest form of M-files) - Functions, which can accept input arguments and return output arguments. Internal variables are local to the function.

ELG 3125 Signal and System Analysis

P. 30

MATLAB M-Files
An example of Script M-files
- Creat a file by the name myscript.m - Contents of myscript.m:
x=45*pi/180; %convert degrees to radians a=sin(x); %compute sine 45 degrees b=cos(x); %compute cosine 45 degrees disp('sin(45*pi/180)='); %print header disp(a); %print result

- Run myscript.m:

ELG 3125 Signal and System Analysis

P. 31

MATLAB M-Files
An example of Function M-files
- Create a file by the name cosgen.m - FUNCTION Add new function - Contents of cosgen.m:
function [ y ] = cosgen ( x,a,f,p ) % COSGEN genreation of a cosine wave % y = cosgen (s, a, f, p) % y - cosine of x; % a - amplitude; % f - frequency; % p - phase y=a*cos(2*pi*f*(x+p/(2*pi*f)));

y output argument x,a,f,p input arguments

ELG 3125 Signal and System Analysis

P. 32

MATLAB M-Files
An example of Function M-files (cont.)
- run the cosgen.m

ELG 3125 Signal and System Analysis

P. 33

MATLAB M-Files
An example of Function M-files (cont.)
- Hint: All the comments at the beginning of a Function M-file will be displayed as help content.

ELG 3125 Signal and System Analysis

P. 34

MATLAB M-Files
Editing M-files through Editor Window
- Use the Editor/Debugger to create and debug M-files, which are programs you write to run MATLAB functions. - The Editor/Debugger provides a GUI for basic text editing, as well as for M-file debugging.
Create a new M-file: File -> New -> M-file Open an M-file: File -> Open

ELG 3125 Signal and System Analysis

P. 35

MATLAB Built-in Functions


MATLAB also has many built-in functions
- >> abs(x) - >> exp(x) - >> fix(x) - >> sqrt(x) - >> log10(x), log(x) Absolute value Exponential value Round towards zero Square root Common (base 10) logarithm, Natural logarithm

- >> round(x), ceil(x) Round towards nearest integer, Round towards plus infinity - >> sin(x), cos(x) - >>max(x), min(x) Sine, Cosine Largest, Smallest component
P. 36

- >> size(x), length(x) Size of array, Length of vector

ELG 3125 Signal and System Analysis

MATLAB Graphics
MATLAB supports a number of plot types with the ability to create customized graphs. The simplest x-y type plot can be created by plot(x,y) To find out about the syntax for any of the plot commands, you can type help <commandname> inside of MATLAB The figure plotted will be shown in the Figure Window.

ELG 3125 Signal and System Analysis

P. 37

MATLAB Graphics
Graph Functions (Summary)
>> >> >> >> >> >> >> >> >> >> plot stem grid xlabel ylabel title subplot figure pause axis linear plot discrete plot add grid lines add X-axis label add Y-axis label add graph title divide figure window create new figure window wait for user response control axis scaling and appearance

ELG 3125 Signal and System Analysis

P. 38

MATLAB Graphics
Some simple examples
x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x = 0:2\pi') ylabel('Sine of x') title('Plot of the Sine Function')
Plot of the Sine Function 1 0.8 0.6 0.4 0.2 Sine of x 0 -0.2 -0.4 -0.6 -0.8 -1

3 x = 0:2

ELG 3125 Signal and System Analysis

P. 39

MATLAB Graphics
Some simple examples (cont.)
t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); plot(t,y1,t,y2) grid on
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1

ELG 3125 Signal and System Analysis

P. 40

MATLAB Graphics
Some simple examples (cont.)
t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); subplot(2,2,1) plot(t,y1) subplot(2,2,2) plot(t,y2)
1 0.5 0 -0.5 -1 1 0.5 0 -0.5 -1

ELG 3125 Signal and System Analysis

P. 41

MATLAB Graphics
Some simple examples (cont.)
0.18

k=0:20; y=binopdf(k,20,0.5); stem(k,y) binopdf(): Binomial probability density function

0.16 0.14 0.12 0.1 0.08 0.06 0.04 0.02 0

10

12

14

16

18

20

ELG 3125 Signal and System Analysis

P. 42

Where to get help?


In Matlabs prompt type:
>>help >>lookfor >>helpwin >>demos >>doc Display help text in Command Window. Search all M-files for keyword. Online help displayed in the Help window. Examples and demonstrations. Display HTML documentation in the Help browser.

>>helpdesk Comprehensive hypertext documentation.

ELG 3125 Signal and System Analysis

P. 43

Where to get help?


On the web:

ELG 3125 Signal and System Analysis

P. 44

End of Lab 1. Thank you.

Any Questions?

ELG 3125 Signal and System Analysis

P. 45