Comm. Sys Lab: SPRING 2013
Comm. Sys Lab: SPRING 2013
SYS LAB
SPRING 2013
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/
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
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.
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
Complex numbers in MATLAB are represented in rectangular form. To separate real & imaginary part
H = real(X) K= imag(X)
, % ;
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
./
.\ + : .^ '
*
/ \ ^
Matrix multiplication
Matrix right division Matrix left division Matrix power
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]
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
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
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
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
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
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.
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
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
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 working directory is controlled by >> dir >> cd catalogue >> pwd The path variable defines where matlab searches for m-files >> path >> addpath
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
Script files
Script-files contain a sequence of Matlab commands factscript.m
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
factfun.m
>> y=factfun(10);
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
y = sum(x)/m;
Function Code
Flow Control
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
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
fact.m
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)]);
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
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
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
and
coordinates of the
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(x,y,line specifiers)
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
--.
plot(x,y)
plot(x,y,r) plot(x,y,--y)
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.
>> year = [1988:1:1994]; >> sales = [127, 130, 136, 145, 158, 178, 211]; >> plot(year,sales,'--r*')
Plot title
1200
Legend
y axis label
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.
xlabel(string)
Adds the string as a label to the x-axis.
ylabel(string)
Adds the string as a label to the y-axis.
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.
Syntax: Example:
color
line
marker
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
marker
Subplots
subplot divides the current figure into rectangular panes that are numbered rowwise.
Syntax:
...
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
Writing m-files
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