Matlab Tutorial
Matlab Tutorial
Matlab Tutorial
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.
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
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
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
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.
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 its 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)
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.
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
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: 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]
matrix = 1 4 7 2 5 8 3 6 9
rowvec =
4 5 6
Concatenation
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 (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
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
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
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
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
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
Outline
Topics to be covered: Programming environment and search path M-files Flow Control Plotting in Matlab Matlab help System
Matlab Environment
Matlab Construction:
Additional
Contr. Syst.
User defined
C-kernel
Core m-files
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
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
end;
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)]);
slow.m
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 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.
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 plot.
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)
plot(x,y,line specifiers)
Line Style
Specifier
--.
b c m
y k
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*')
Legend
Text
800
Tick-mark
Comparison between theory and experiment.
INTENSITY (lux)
600
400
Data symbol
200
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.
Formatting Commands
legend(string1,string2,string3)
Creates a legend using the strings to label various curves (when several curves are in one plot). The
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
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
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
Writing m-files
Header (function definition), comments, program body Flow control: if...elseif...if, for, while General-purpose functions: use functions as inputs
Plotting in Matlab
Plot, subplot
THE END