COMM.
SYS LAB
SPRING 2013
Iqra University, Islamabad Campus
LAB 1
INTRODUCTION TO MATLAB
What is Matlab ?
What is Matlab ?
*MATLAB is a programming environment for algorithm development, data analysis, visualization, and numerical computation. Using MATLAB, you can solve technical computing problems faster than with traditional programming languages, such as C, C++, and Fortran.
*http://www.mathworks.com/
What is Matlab? cont.
A software environment for interactive numerical computations Matlab (stands for MATrix LABoratory)
Applications:
Communications Systems Computational Biology Computational Finance Control Systems Digital Signal Processing Embedded Systems FPGA Design Image and Video Processing Mechatronics Technical Computing Test and Measurement
Strengths of MATLAB
MATLAB is relatively easy to learn Help is too extensive Great built-in functions support Numerous toolboxes, blocksets and Simulink for modeling real world engineering problems MATLAB code is optimized to be relatively quick when performing matrix operations MATLAB may behave like a calculator or as a programming language MATLAB is interpreted, errors are easier to fix State of the art Graphical User Interface
Matlab Interface
Command Window
Use the Command Window to enter variables and run functions and M-files.
Command History
Statements you enter in the Command Window are logged in the Command History. In the Command History, you can view previously run statements, and copy and execute selected statements.
Workspace Browser
The MATLAB workspace consists of the set of variables (named arrays) built up during a MATLAB session and stored in memory.
Array Editor
Matlab: Variable Names
Variable names ARE case sensitive Variable names can contain up to 63 characters Variable names must start with a letter followed by letters, digits, and underscores. Blanks are NOT allowed in a variable name, however _ is allowed.
MATLAB special variables
ans pi inf NaN i and j eps realmin number realmax number
Default variable name for results Value of Infinity Not a number e.g. 0/0 i = j = imaginary number Smallest incremental number The smallest usable positive real The largest usable positive real
Examples:
>> a=2
a=
>> 2*pi
ans =
6.2832
Types of Variables
Type Integer Real Complex
Examples 1362,-5656 12.33,-56.3 X=12.2 3.2i -- (i = sqrt(-1))
Complex numbers in MATLAB are represented in rectangular form. To separate real & imaginary part
H = real(X) K= imag(X)
Conversion between polar & rectangular
C1= 1-2i Magnitude: mag_c1 = abs(C1) Angle: angle_c1 = angle(C1)
Note that angle is in radians
Other MATLAB symbols
, % ;
separate statements and data start comment which ends at end of line Shortcut Ctrl+R, Ctrl+T (1) suppress output (2) used as a row separator in a matrix specify range
Arithmetic Operators
Operator + .* Addition Subtraction Multiplication (element wise) Description
./
.\ + : .^ '
Right division (element wise)
Left division (element wise) Unary plus Unary minus Colon operator Power (element wise) Transpose
*
/ \ ^
Matrix multiplication
Matrix right division Matrix left division Matrix power
Relational & Logical Operators
Operator & | Description Returns 1 for every element location that is true (nonzero) in both arrays, and 0 for all other elements. Returns 1 for every element location that is true (nonzero) in either one or the other, or both, arrays and 0 for all other elements. Complements each element of input array, A. Less than Less than or equal to Greater than Greater than or equal to Equal to Not equal to
~ < <= > >= == ~=
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
MATLAB Matrices
A matrix can be created in MATLAB as follows (note the commas AND semicolons): matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9] matrix =
1 4 7
2 5 8
3 6 9
Row Vector:
A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas): rowvec = [12 , 14 , 63] rowvec = 12 14 63 Row vector can also defined in a following way: rowvec = 2 : 2 : 10;
rowvec = 2 4 6 8 10
Column Vector:
A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows (note the semicolons): colvec = [13 ; 45 ; -2]
colvec =
13 45 -2
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.
Extracting a Sub-Matrix
A row vector can be extracted from a matrix. As an example we create a matrix below:
matrix=[1,2,3;4,5,6;7,8,9] matrix = 1 2 3
Here we extract row 2 of the matrix and make a row vector. Note that the 2:2 specifies the second row and the 1:3 specifies which columns of the row.
rowvec=matrix(2 : 2 , 1 : 3) rowvec =
4
7
5
8
6
9
Concatenation
New matrices may be formed out of old ones Suppose we have: >> a = [1 2 5; 3 4 6; 6 8 9]; b = a(1:2 , 1:2); c = a(1 , :); d = a(2:3 , :); e = a[d ;d]; b = ?? c = ?? d = ?? e = ??
Concatenation
Input [a, a, a] Output ans = 1 2 1 2 1 2 343434 ans = 1 2 34 12 34 12 34 ans = 1 2 0 0 3400 0013 0024
[a; a; a]
[a, zeros(2); zeros(2), a']
Useful MATLAB Commands
clear Clear all variables from work space clear x y Clear variables x and y from work space clc Clear the command window who List known variables whos List known variables plus their size lookfor look up whole matlab directory for available functions doc open the html based help window tic toc measure the simulation time of program
Scalar Matrix Addition & Subtraction
a=3; b=[1, 2, 3;4, 5, 6] b= 1 2 3 4 5 6 c= b+a % Add a to each element of b c= 4 5 6 7 8 9
Scalar - Matrix Multiplication
a=3; b=[1, 2, 3; 4, 5, 6] b= 1 2 3 4 5 6 c = a * b % Multiply each element of b by a c= 3 6 9 12 15 18
Other matrices ops:Determinant & Inverse
Let a=[1 4 3;4 2 6 ;7 8 9] det(a) 48 inv(a) ans = -0.6250 -0.2500 0.3750 0.1250 -0.2500 0.1250 0.3750 0.4167 -0.2917
Other matrices Operations cont.
a (Find the transpose of matrix) ans = 1 4 7 4 2 8 3 6 9 min(a) :Return a row vector containing the minimum element from each column. ans =1 2 3 min(min(a)): Return the smallest element in matrix
Other matrices Operations cont.
max(a): Return a row vector containing the maximum element from each column. ans =7 8 9 max(max(a)): Return the max element from matrix: ans = 9 a.^2 :Bitwise calculate the square of each element of matrix: ans = 1 16 9 16 4 36 49 64 81
Other matrices Operations cont.
sum (a): treats the columns of a as vectors, returning a row vector of the sums of each column. ans = 12 14 18 sum(sum(a)): Calculate the sum of all the elements in the matrix. ans = 44
Example
Let a=[1 2 3] ; b=[4 5 6];
a.*b : Bitwise multiply the each element of vector a and b:
ans = 4 10 18
Matrix Division
MATLAB has several options for matrix division. You can right divide and left divide.
Right Division: use the slash character A/B This is equivalent to the MATLAB expression A*inv (B) Left Division: use the backslash character A\B This is equivalent to the MATLAB expression inv (A)*B
Common Matrices and Vectors
Matrix of Zeros - zeros
Matrix of Ones - ones
Identity Matrix eye Magic Matrix - magic
zeros Matrix
Syntax : zeros array Format : zeros(N), zeros(M,N) Description: This function is used to produce an array of zeros, defined by the arguments.
(N) is an N-by-N matrix of array. (M,N) is an M-by-N matrix of array.
Example; >> zeros(2) ans = 0 0 0 0
>> zeros(1,2) ans = 0 0
Ones Matrix
Syntax : ones array Format : ones(N), ones(M,N) Description: This function is used to produce an array of ones, defined by the arguments. (N) is an N-by-N matrix of array. (M,N) is an M-by-N matrix of array. Example; >> ones(2) >> ones(1,2) ans = ans = 1 1 1 1 1 1
Eye Matrix
Syntax : identity matrix Format : eye (N), eye (M,N) Description:
Create an NxN or MxN identity matrix (i.e., 1s on the diagonal elements with all others equal to zero). (Usually the identity matrix is represented by the letter I. Type Example; >> I=eye(3) I= 1 0 0 0 1 0 0 0 1
The Help System
Search for appropriate function >> lookfor keyword
Rapid help with syntax and function definition >> help function An advanced hyperlinked help system is launched by >> helpdesk Complete manuals as PDF files
INTRODUCTION TO MATLAB - cont
Outline
Programming environment and search path M-files Flow Control Plotting in Matlab Matlab help System
Matlab environment
Matlab construction Core functionality as compiled C-code, m-files Additional functionality in toolboxes (m-files)
Today: Matlab programming (construct own m-files)
Sig. Proc Contr. Syst. User defined
C-kernel
Core m-files
The programming environment
The working directory is controlled by >> dir >> cd catalogue >> pwd The path variable defines where matlab searches for m-files >> path >> addpath
The programming environment
Matlab cant tell if identifier is variable or function >> z=theta;
Matlab searches for identifier in the following order
1. variable in current workspace 2. built-in variable 3. built-in m-file 4. m-file in current directory 5. m-file on search path
Note: m-files can be located in current directory, or in path
M-files
MATLAB can execute a sequence of MATLAB statements stored on disk. Such files are called "M-files" they must have the file type of ".m" There are two types of M-files: Script files Function files.
M-files
To make the m-file click on File next select New and click on M-File from the pull-down menu as shown in fig
M-files
Here you will type your code, can make changes, etc. Save the file with .m extension
M-files
Types of M-files Script Files Function Files
Script files
Script-files contain a sequence of Matlab commands factscript.m
%FACTSCRIPT Compute n-factorial, n!=1*2*...*n y = prod(1:n);
Executed by typing its name >> factscript Operates on variables in global workspace
Variable n must exist in workspace Variable y is created (or over-written) Use comment lines (starting with %) to document file!
Functions Functions
Functions describe subprograms
Take
inputs, generate outputs Have local variables (invisible in global workspace)
function [output_arguments]= function_name(input_arguments)
% Comment lines <function body>
factfun.m
>> y=factfun(10);
function [z]=factfun(n) % FACTFUN Compute factorial % Z=FACTFUN(N) z = prod(1:n);
Functions
NOTE: The function_name must also be the same as the file name (without the ``.m'') in which the function is stored
Example
Output Arguments Function Name Input Arguments
Comments
function y = mean (x)
% MEAN Average or mean value. % For vectors, MEAN(x) returns the mean value. % For matrices, MEAN(x) is a row vector % containing the mean value of each column. [m,n] = size(x); if m == 1 m = n; end
y = sum(x)/m;
Function Code
Flow Control
Flow control - selection
The if-elseif-else construction
if <logical expression> <commands> elseif <logical expression> <commands> else <commands> end
if height>170 disp(tall) elseif height<150 disp(small) else disp(average) end
Logical expressions
Relational operators (compare arrays of same sizes) == (equal to) ~= (not equal) < (less than) <= (less than or equal to) > (greater than) >= (greater than or equal to) Logical operators (combinations of relational operators) & (and) | (or) ~ (not) if (x>=0) & (x<=10) Logical functions disp(x is in range [0,10]) xor else isempty disp(x is out of range) any end all
Flow control - selection
The switch construction Switch<expression> case <condition>, <statement> otherwise< condition >, < statement> end
method = 'Bilinear'; switch (method) case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic') case 'nearest' disp('Method is nearest') otherwise disp('Unknown method.') end
Flow control - repetition
Repeats a code segment a fixed number of times
for index=<vector> <statements> end The <statements> are executed repeatedly. At each iteration, the variable index is assigned a new value from <vector>.
for k=1:12 kfac=prod(1:k); disp([num2str(k), ,num2str(kfac)]) end
Example selection and repetition
function y=fact(n) % FACT Display factorials of integers 1..n if n < 1 error(No input argument assigned) elseif n < 0 error(Input must be non-negative) elseif abs(n-round(n)) > eps error(Input must be an integer) end for k=1:n kfac=prod(1:k); disp([num2str(k), ,num2str(kfac)]) y(k)=kfac; end;
fact.m
Flow control conditional repetition
while-loops
while <logical expression> <statements> end <statements> are executed repeatedly as long as the <logical expression> evaluates to true k=1; while prod(1:k)~=Inf, k=k+1; end disp([Largest factorial in Matlab:,num2str(k)]);
Programming tips and tricks
X=-250:0.1:250; for ii=1:length(x) if x(ii)>=0, s(ii)=sqrt(x(ii)); else s(ii)=0; end; end; toc
Programming style has huge influence on tic; program speed! slow.m
tic x=-250:0.1:250; s=sqrt(x); s(x<0)=0; toc;
fast.m
Loops are slow: Replace loops by vector operations! Memory allocation takes a lot of time: Pre-allocate memory!
Break Command
Terminate execution of WHILE or FOR loop. In nested loops, BREAK exits from the innermost loop only. BREAK is not defined outside of a FOR or WHILE loop.
n = 1; while prod(1:n) < 700 n = n + 1; if n==5 break; end end
Plotting in Matlab
TWO-DIMENSIONAL plot() COMMAND
The basic 2-D plot command is:
plot(x,y)
where x is a vector (one dimensional array), and y is a vector. Both vectors must have the same number of elements. The plot command creates a single curve with the the abscissa (horizontal axis) and the (vertical axis).
values on
values on the ordinate
The curve is made from segments of lines that connect the
points that are defined by the elements in the two vectors.
and
coordinates of the
PLOT OF GIVEN DATA
Given data: x y 1 2 2 6.5 3 7 5 7 7 5.5 7.5 4 8 6 10 8
A plot can be created by the commands shown below. This can be done in the Command Window, or by writing and then running a script file.
>> x=[1 2 3 5 7 7.5 8 10]; >> y=[2 6.5 7 7 5.5 4 6 8]; >> plot(x,y)
Once the plot command is executed, the Figure Window opens with the following plot.
PLOT OF GIVEN DATA
LINE SPECIFIERS IN THE plot() COMMAND
Line specifiers can be added in the plot command to:
Specify the style of the line.
Specify the color of the line. Specify the type of the markers (if markers are desired).
plot(x,y,line specifiers)
LINE SPECIFIERS IN THE plot() COMMAND
plot(x,y,line specifiers)
Line Style
Specifier
Line Specifier Marker Specifier Color Type red green blue Cyan magenta yellow black r g b c m y k plus sign + circle o asterisk * point . square s diamond d
Solid dotted : dashed dash-dot
--.
LINE SPECIFIERS IN THE plot() COMMAND
The specifiers are typed inside the plot() command as strings. Within the string the specifiers can be typed in any order. The specifiers are optional. This means that none, one, two, or all the three can be included in a command. EXAMPLES:
plot(x,y)
plot(x,y,r) plot(x,y,--y)
A solid blue line connects the points with no markers.
A solid red line connects the points with no markers. A yellow dashed line connects the points.
plot(x,y,*)
plot(x,y,g:d)
The points are marked with * (no line between the points.)
A green dotted line connects the points which are marked with diamond markers.
PLOT OF GIVEN DATA USING LINE SPECIFIERS IN THE plot() COMMAND
Year Sales (M) 1988 127 1989 130 1990 136 1991 145 1992 158 1993 178 1994 211
>> year = [1988:1:1994]; >> sales = [127, 130, 136, 145, 158, 178, 211]; >> plot(year,sales,'--r*')
Line Specifiers: dashed red line and asterisk markers.
PLOT OF GIVEN DATA USING LINE SPECIFIERS IN THE plot() COMMAND
Dashed red line and asterisk markers.
Formatting the plots
Plot title
1200
EXAMPLE OF A FORMATTED 2-D PLOT
Light Intensity as a Function of Distance
Legend
y axis label
Theory Experiment 1000
Text
800
Tick-mark
Comparison between theory and experiment.
INTENSITY (lux)
600
400
Data symbol
200
10
12
14
16 18 DISTANCE (cm)
20
22
24
x axis label
Tick-mark label
FORMATTING PLOTS
A plot can be formatted to have a required appearance. With formatting you can: Add title to the plot. Add labels to axes. Change range of the axes. Add legend. Add text blocks. Add grid.
FORMATTING COMMANDS title(string)
Adds the string as a title at the top of the plot.
xlabel(string)
Adds the string as a label to the x-axis.
ylabel(string)
Adds the string as a label to the y-axis.
axis([xmin xmax ymin ymax])
Sets the minimum and maximum limits of the x- and y-axes.
FORMATTING COMMANDS
legend(string1,string2,string3)
Creates a legend using the strings to label various curves (when several curves are in one plot). The location of the legend is specified by the mouse.
text(x,y,string)
Places the string (text) on the plot at coordinate x,y relative to the plot axes.
Example of a formatted plot
Syntax: Example:
color
line
marker
plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)
x=[0:0.1:2*pi]; y=sin(x); z=cos(x); plot(x,y,x,z) title('Sample Plot','fontsize',14); xlabel('X values','fontsize',14); ylabel('Y values','fontsize',14); legend('Y data','Z data') grid on
Sample Plot
Title
Ylabel
Grid
Legend Xlabel
EXAMPLE OF A FORMATTED PLOT
Syntax:
Example:
x=[0:0.1:2*pi]; y=sin(x); z=cos(x); plot(x,y,x,z) title('Sample Plot','fontsize',14); xlabel('X values','fontsize',14); ylabel('Y values','fontsize',14); legend('Y data','Z data') grid on color line
marker
plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)
Displaying Multiple Plots
Two typical ways to display multiple curves in MATLAB (other combinations are possible) One figure contains one plot that contains multiple curves Requires the use of the command hold (see MATLAB help) One figure contains multiple plots, each plot containing one curve Requires the use of the command subplot
Sample plot [using hold on command]
x=[0:0.1:2*pi]; y=sin(x); z=cos(x); plot(x,y,x,z) grid on x=[0:0.1:2*pi]; y=sin(x); z=cos(x); plot(x,y,b) hold on plot(x,z,g) hold off grid on
Subplots
subplot divides the current figure into rectangular panes that are numbered rowwise.
Syntax:
subplot(rows,cols,index) subplot(2,2,1); subplot(2,2,2) ... subplot(2,2,3)
...
subplot(2,2,4) ...
Example of subplot
x=[0:0.1:2*pi]; y=sin(x); z=cos(x); subplot(1,2,1); plot(x,y) subplot(1,2,2) plot(x,z) grid on
Summary
User-defined functionality in m-files Script-files vs. functions
Stored in current directory, or on search path
Functions have local variables, Scripts operate on global workspace
Writing m-files
Programming style and speed
Header (function definition), comments, program body Flow control: if...elseif...if, for, while General-purpose functions: use functions as inputs
Vectorization, memory allocation, profiler Plot, subplot
Plotting in Matlab
THE END