MATLAB BY:
AMMAR AJMAL
Iqra University, Islamabad Campus
Version Installed in C & SP Lab
What is Matlab ? *MATLAB® is a high-level language and interactive environment that enables you to perform computationally intensive tasks faster than with traditional programming languages such as C, C++, and Fortran. (true??)
http://www.mathworks.com/
Domains of Usage Matlab (stands for MATrix LABoratory) A software environment for interactive numerical computations
Example Domains: Matrix computations and linear algebra Solving nonlinear equations Numerical solution of differential equations Mathematical optimization Statistics and data analysis Signal processing Modelling of dynamical systems Solving partial differential equations Simulation of engineering systems
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
LAB 1
INTRODUCTION TO MATLAB
Matlab *MATLAB is a numerical computation and simulation tool that was developed into a commercial tool with a user friendly interface from the numerical function libraries LINPACK and EISPACK, which were originally written in the FORTRAN programming language.
* Introduction to Matlab® & Simulink - A Project Approach, Third Edition O. Beucher and M. Weeks
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
Useful Built-in Commands
clear clear x y clc who whos lookfor doc tic toc
Clear all variables from work space Clear variables x and y from work space Clear the command window List known variables List known variables plus their size look up whole matlab directory for available functions open the html based help window measure the simulation time of program
MATLAB Built-in Variables
ans pi inf NaN i and j eps realmin realmax
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 number The largest usable positive real number
Built-in Keywords
Checking whether input is MATLAB keyword:
Iskeyword
>>iskeyword ans = 'break' 'case' 'catch' 'classdef' 'continue' 'else' 'elseif' 'end' 'for' 'function' 'global'
'if' 'otherwise' 'parfor' 'persistent' 'return' 'spmd' 'switch' 'try' 'while'
Matlab Variables A MATLAB variable is an object belonging to a specific data type. In Matlab a variable is basically a matrix and matrices can be made up of real or complex numbers, as well as characters (ASCII symbols).
Matlab Variables
A MATLAB variable is essentially a tag that you assign to a value while that value remains in memory. The tag gives you a way to reference the value in memory so that your programs can read it, operate on it with other data, and save it back to memory.
Rules for Variable Names
Variable names can contain up to 63 characters, and can be checked by: N = namelengthmax N = 63
Variable Names are Case Sensitive
Do Not Use Function Names for Variables
Variable names must start with a letter followed by letters, digits, and underscores.
Blanks are NOT allowed in a variable name, however “_” is allowed.
Verifying Validity of a Variable Name isvarname 8th_column (checks whether it’s a valid name or not)
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
Variable Types based on Usage
MATLAB provides three basic types of variables: Local
Variables Global Variables Persistent Variables
Variable Types Local Variables Each MATLAB function has its own local variables. These are separate from those of other functions (except for nested functions), and from those of the base workspace. Variables defined in a function do not remain in memory from one function call to the next, unless they are defined as global or persistent. Scripts, on the other hand, do not have a separate workspace. They store their variables in a workspace that is shared with the caller of the script. When called from the command line, they share the base workspace. When called from a function, they share that function's workspace. Note If you run a script that alters a variable that already exists in the caller's workspace, that variable is overwritten by the script.
Variable Types Global Variables If several functions, and possibly the base workspace, all declare a particular name as global, then they all share a single copy of that variable. Any assignment to that variable, in any function, is available to all the other functions declaring it global.
global ALPHA BETA
Variable Types Persistent Variables Characteristics of persistent variables are
You can declare and use them in functions only. Only the function in which the variables are declared is allowed access to it. MATLAB does not clear them from memory when the function exits, so their value is retained from one function call to the next. You must declare persistent variables before you can use them in a function.
It is usually best to put your persistent declarations toward the beginning of the function. You would declare persistent variable SUM_X as follows:
persistent SUM_X
Defining a Variable
Row and Column Vectors If no variable name is set, MATLAB assigns the name ans (answer) to the result, as the following example shows:
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
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]
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)
matrix = 1
2
3
4
5
6
7
8
9
rowvec = 4
5
6
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
Output
[a, a, a]
ans = 1 2 1 2 1 2 343434
[a; a; a]
ans = 1 2 34 12 34 12 34
[a, zeros(2); zeros(2), a']
ans = 1 2 0 0 3400 0013 0024
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
Matlabs’ Built-in 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., 1’s 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
LAB 2
INTRODUCTION TO MATLAB - cont
Outline Topics to be covered: 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
C-kernel
Contr. Syst.
Core m-files
User defined
Matlab Environment – cont.
Matlab can’t 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
>> y=factfun(10);
factfun.m
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
Comments
Function Name
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
Input Arguments
Flow Control
Flow control - selection
The if-elseif-else construction if elseif else 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 case , 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= end The are executed repeatedly. At each iteration, the variable index is assigned a new value from .
for k=1:12 kfac=prod(1:k); disp([num2str(k),’ ‘,num2str(kfac)]) end
Example – selection and repetition fact.m
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;
Flow control – conditional repetition
while-loops while end are executed repeatedly as long as the 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
Programming style has huge influence on program speed! slow.m
tic; 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
tic x=-250:0.1:250; s=sqrt(x); s(x<0)=0; toc;
•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
2-D Plot Command
The basic two dimensional plot command in Matlab 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 x values on the abscissa (horizontal axis) and the y values on the ordinate (vertical axis), The curve is made from segments of lines that connect the points that are defined by the x and y coordinates of the elements in the two vectors.
Plot of a given data Given Data:
x
1
2
3
5
7
7.5
8
10
y
2
6.5
7
7
5.5
4
6
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 plot.
The plot window
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
Solid dotted : dashed dash-dot
-
--.
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
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)
A solid blue line connects the points with no markers.
plot(x,y,’r’)
A solid red line connects the points with no markers.
plot(x,y,’--y’)
A yellow dashed line connects the points.
plot(x,y,’*’)
The points are marked with * (no line between the points.)
plot(x,y,’g:d’)
A green dotted line connects the points which are marked with diamond markers.
Speicifiers in the Plot Command Year
1988
1989
1990
1991
1992
1993
1994
Sales (M)
127
130
136
145
158
178
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.
Specifiers in the Plot Command
Dashed red line and asterisk markers.
Formatting the plots
Example of a formatted 2-D Plot Light Intensity as a Function of Distance
Plot title
Legend
1200 Theory Experiment
y axis label
1000
Text Tick-mark
INTENSITY (lux)
800 Comparison between theory and experiment. 600
400
Data symbol 200
0
8
x axis 10 label
12
14
16 18 DISTANCE (cm)
20
22
24
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:
color
line
marker
plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)
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
Sample Plot Title
Ylabel
Grid
Legend Xlabel
EXAMPLE OF A FORMATTED PLOT Syntax:
color
line
marker
plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)
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
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
Header (function definition), comments, program body Flow control: ”if...elseif...if”, ”for”, ”while” General-purpose functions: use functions as inputs
Programming style and speed
Functions have local variables, Scripts operate on global workspace
Writing m-files
Stored in current directory, or on search path
Vectorization, memory allocation, profiler
Plotting in Matlab
Plot, subplot
THE END