Professional Documents
Culture Documents
Matrix Laboratory
Introduction to Matlab
By Dr. Kourosh Kiani
Course Structure
Introduction
History of MATLAB
Ancestral software to MATLAB Fortran subroutines for solving linear (LINPACK) and eigenvalue (EISPACK) problems In 1970, Cleve Moler, the chairman of the computer science department at University of New Mexico, designed MATLAB to give his students to access LINPACK and EISPACK without requiring knowledge of Fortran
Later, when teaching courses in mathematics, Moler wanted his students to be able to use LINPACK and EISPACK without requiring knowledge of Fortran MATLAB developed as an interactive system to access LINPACK and EISPACK
It soon spread to other universities and found a strong audience within the applied mathematics community. MATLAB gained popularity primarily through word of mouth because it was not officially distributed In1984, Jack Little, Cleve Moler and Steve Bangert rewrote MATLAB in C with more functionality (such as plotting routines).
The Mathworks, Inc. was created in 1984 The Mathworks is now responsible for development, sale, and support for MATLAB The Mathworks is located in Natick, MA
What Is MATLAB? MATLAB (MATrix LABoratory) high-performance language for technical computing computation, visualization, and programming in an easy-to-use environment Typical uses include: Math and computation Algorithm development Modelling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including Graphical User Interface building
Why MATLAB
A good choice for vision program development because: Easy to do very rapid prototyping Quick to learn, and good documentation A good library of image processing functions Excellent display capabilities Widely used for teaching and research in universities and industry MATLAB code is optimized to be relatively quick when performing matrix operations MATLAB may behave like a calculator or as a programming language
Has some drawbacks: Slow for some kinds of processes Not geared to the web Not designed for large-scale system development Not a general purpose programming language MATLAB is an interpreted language (making it for the most part slower than a compiled language such as C++)
MATLAB Components
MATLAB Components
The MATLAB function library. a vast collection of computational algorithms ranging from elementary functions like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms as well as special image processing related functions The MATLAB Application Program Interface (API) a library that allows you to write C and Fortran programs that interact with MATLAB. It include facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files.
MATLAB
Some facts for a first impression Everything in MATLAB is a matrix ! MATLAB is an interpreted language, no compilation needed (but possible) MATLAB does not need any variable declarations, no dimension statements, has no packaging, no storage allocation, no pointers Programs can be run step by step, with full access to all variables, functions etc.
Opening MatLAB
Open MatLAB by Clicking on the desktop icon or finding MatLAB on the Start menu
MATLAB Environment
MATLAB
MatLAB window
Contents of CWD Current working Directory (CWD)
Watch and manipulate your variables Write different MATLAB commands, and watch most of the results
Command Window
Workspace
Allows access to data Area of memory managed through the Command Window Shows Name, Size (in elements), Number of Bytes and Type of Variable
Current Directory
MATLAB, like Windows or UNIX, has a current directory MATLAB functions can be called from any directory Your programs (to be discussed later) are only available if the current directory is the one that they exist in
To add path
File Set Path
Add Folder
Command History
Allows access to the commands used during this session, and possibly previous sessions Clicking and dragging to the Command window allows you to re-execute previous commands
Command Window
Probably the most important part of the GUI Allows you to input the commands that will create variables, modify variables and even (later) execute scripts and functions you program yourself.
MatLAB interface has four important features Current working directory drop-down box Command window (human interface) Command history window Contents of CWD
command files
When you type the name of a command, MatLAB begins looking for a .m file with that name Search begins in the Current Working Directory (CWD) Best Practice is to set CWD to you network (?:) drive
Command files
Command files may be Internal MatLAB functions User-defined script file User-defined function file
Matlab Programs
Matlab is an extravagant calculator if all we can do is execute commands typed into the Command Window So how can we execute a program? Programs in Matlab are:
Scripts, or Functions
Scripts: Matlab statements that are fed from a file into the Command Window and executed immediately Functions: Program modules that are passed data (arguments) and return a result (i.e., sin(x)) These can be created in any text editor (but Matlab supplies a nice built-in editor)
Global variables are known everywhere Any variable defined in the command window is global Any variable defined in a script is global Local variables are known only in the current program segment (function file)
Simple Script
Ask user for name Output string welcoming name to Dr. Kiani Lecture Save as welcome.m
M-files
M-files are macros of MATLAB commands that are stored as ordinary text files with the extension "m", that is filename.m example of an M-file that defines a function, create a file in your working directory named yplusx.m that contains the following commands: Write this file: function z = yplusx(y,x) z = y + x; -save the above file(2lines) as yplusx.m x = 2; y = 3; z = yplusx(y,x) 5 Get input by prompting on m-file: T = input('Input the value of T: ')
A semi-colon ; suppresses echo of MatLAB commands Square brackets [ ] are used to collect or concatenate like items in MatLAB The input() function is used to prompt user for input in the command window The disp() function is used to display strings or variables in the command window
Note that the input value Semnan must be enclosed in single tick marks so MatLAB knows it is a string variable
MatLAB commands may be either Script or Function type Script file No parameters (arguments) No return value Uses global address space Function file May take parameters Typically returns one or more values Uses local address space
MATLAB program design fundamentals MATLAB variable name conventions Starting with a letter followed by other characters Case sensitive. Abc ABc are different Valid variable names: MYvar12, MY_Var12 and MyVar12_ Invalid variable names: 12MyVar, _MyVar12 MATLAB reserved variables/constants eps, i, j, pi, NaN, Inf, i=sqrt(-1) lastwarn, lasterr
Reserved Words
Matlab has some special (reserved) words that you may not use for end if while function return elsif case otherwise switch continue else try catch global persistent break
ans beep pi eps inf NaN i (or) j realmin, realmax bitmax nargin, nargout varargin varaout
default variable name for results make sound mathematical constant smallest number that can be subtracted from 0 to make a negative infinity not a number imaginary number smallest & largest positive real numbers largest positive integer number of function in (or) out variables variable number of function in args variable number of function out args
abs(x) absolute value sqrt(x) square root round(x) rounds to nearest fix(x) truncates toward 0 floor(x) rounds down ceil(x) rounds up
sign(x) sign of x rem(x,y) remainder of x/y exp(x) e raised to x power log(x) natural log of x log10(x) log to the base 10 log2(x) log to the base 2
Notice that MATLAB wants angles to be expressed in radians, not degrees. To convert use the relationship 1 degree = pi/180 radians angle_radians = angle_degrees*(pi/180) angle_degrees = angle_radians*(180/pi)
max(x), min(x), mean(x), median(x), std(x), sum(x), prod(x), cumsum(x), cumprod(x), sort(x), size(x), length(x) are just a few. Note that x may be a vector (row or column) or a matrix. For matrices, functions typically work on the columns of the matrix to yield their results.
Simple Commands
who whos save clear load
who
who lists the variables currently in the workspace. As we learn more about the data structures available in MATLAB, we will see more uses of who
whos
whos is similar to who, but also gives size and storage information s = whos(...) returns a structure with these fields name variable name size variable size bytes number of bytes allocated for the array class class of variable and assigns it to the variable s. (We will discuss structures more).
Save
save saves workspace variables on disk save filename stores all workspace variables in the current directory in filename.mat save filename var1 var2 ... saves only the specified workspace variables in filename.mat. Use the * wildcard to save only those variables that match the specified pattern.
Clear
clear removes items from workspace, freeing up system memory Examples of syntax:
clear clear name clear name1 name2 name3 ...
clc
Not quite clear clc clears only the command window, and has no effect on variables in the workspace.
Load
Matlab Help
This variable may be subsequently used >> 91.3 14 ans = 77.3 >> z=ans * 2 z= 154.6
>>z z= 144.6
A semicolon should be used on most lines of code as we are not interested in intermediary results
Complex Numbers
Matlab implicitly supports complex numbers
no requirement for special functions to manipulate
Complex Numbers - 2
z3=5.6*sin(1.55)*i z3 = 0+ 5.5988i r1=imag(z3) r1 = 5.5988 z4=mean([z1 z2 z3]) z4 = 2.6667+ 2.1996i
Complex Numbers - 3
Note: mathematical and built-in function usage is exactly the same as for non-complex complex expressions yield complex values
Matlab has two special "constants" which are substituted when such operations occur:
NaN Inf Not a Number Infinity
Strings
Not all real-world objects are best represented by numbers e.g., names, addresses, units of measurement A common type supported by most languages (including Matlab) is the String a collection of characters Indicated by the single-quote '
Strings
A string is an array of characters s = 'abc' is equivalent to s = [ 'a' 'b' 'c' ] All operations that apply to vectors and arrays can be used together with strings as well s(1) p 'a' s( [ 1 2 ] ) = 'XX' p s = 'XXc' s(end) p 'c'
String Conversion
Conversion of strings to numerical arrays double( 'abc xyz' ) ans = 97 98 99 32 120 121 122 double( 'ABC XYZ' ) ans = 65 66 67 32 88 89 90 Conversion of numerical arrays to strings char( [ 72 101 108 108 111 33 ] ) ans = Hello!
Character Arrays
2-D character arrays s = [ 'my first string'; 'my second string' ] ??? Error s = char( 'my first string', 'my second string' ) s= char function my first string automatically my second string pads strings size(s) p [ 2 16 ] size( deblank( s(1,:) ) ) p [ 1 15 ]
String Tests
ischar() : returns 1 for a character array ischar ( 'CS 111' ) ans = 1 isletter() : returns 1 for letters of the alphabet isletter( 'CS 111' ) ans = 1 1 0 0 0 0 isspace() : returns 1 for whitespace (blank, tab, new line) isspace( 'CS 111' ) ans = 0 0 1 0 0 0
String Comparison
Comparing two characters 'a' < 'e' ans = 1 Comparing two strings character by character 'fate' == 'cake' ans = 0 1 0 1 'fate' > 'cake' ans = 1 0 1 0
String Comparison
strcmp() : returns 1 if two strings are identical a = 'Bilkent'; strcmp( a, 'Bilkent' ) ans = 1 strcmp( 'Hello', 'hello' ) ans = 0 strcmpi() : returns 1 if two strings are identical ignoring case strcmpi( 'Hello', 'hello' ) ans = 1
String Comparison
>> str1='My first string' str1 = My first string >> findstr(str1,'first') ans = 4 >> strcmp(str1,'My') ans = 0
Strings
>> strncmp(str1,'My',2) ans = 1 >> str2='45.6' str2 = 45.6 >> str2num(str2) ans = 45.6000
Strings
>> str1 str1 = My first string >> str2 str2 = 45.6 >> strcat(str1,str2) ans = My first string45.6
Searching in Strings
findstr() : finds one string within another one test = 'This is a test!'; pos = findstr( test, 'is' ) pos = 3 6 pos = findstr( test, ' ' ) pos = 5 8 10
Replacing in Strings
strrep() : replaces one string with another s1 = 'This is a good example'; s2 = strrep( s1, 'good', 'great' ) s2 = This is a great example
String Conversion
Recall num2str() for numeric-to-string conversion str = [ 'Plot for x = ' num2str( 10.3 ) ] str = Plot for x = 10.3 str2num() : converts strings containing numbers to numeric form x = str2num( '3.1415' ) x= 3.1415
Managing Variables
The variables created during a Matlab session are not persistent objects: they cease to exist when the session is over endure for the duration of the session Matlab provides the following command for managing the workspace clear delete a variable now
Managing Variables - 2
>> x=7.9 x = 7.9000 >> clear x >> x ??? Undefined function or variable 'x'. Useful if you wish to ensure that a variable starts with no value
initialisation
10
>> save linear >> clear linear >> linear ??? Undefined function or variable 'linear'.
10
36 49 64 81 100
>> save mydata linear squares >> clear linear squares >> squares ??? Undefined function or variable 'squares'.
Command Explanation
Format Examples
format instructions should be used in conjunction with disp to ensure the output answers are in the most appropriate form. Note: format does not change the actual value of the variable being displayed, it simply alters the display format. >> format short; disp(pi); 3.1416 >> format long; disp(pi); 3.14159265358979
Format Examples - 2
>> format short e; disp(pi); 3.1416e+00 >> format long e; disp(pi); 3.141592653589793e+00 >> format short g; disp(pi); 3.1416 >> format long g; disp(pi); 3.14159265358979
Format Examples - 3
>> format hex; disp(pi); 400921fb54442d18 >> format bank; disp(pi); 3.14 >> format +; disp(pi); + >> format rat; disp(pi); 355/113
Questions?