You are on page 1of 53

Introduction to MATLAB

What is MATLAB?
MATLAB is a package that has been purpose-designed to make computations easy, fast and reliable. It is installed on machines run by Bath University Computing Services (BUCS), which can be accessed in the BUCS PC Labs such as those in 1 East 3.9, 1 West 2.25 or 3 East 3.1, as well as from any of the PCs in the Library. The machines which you will use for running MATLAB are SUN computers that run on the UNIX operating system. (If you are a PC or Mac fan, note that this is a quite deferent environment from what you are used to. However you will need only a small number of UNIX commands when you are working with MATLAB. MATLAB started life in the 1970s as a user-friendly interface to certain clever but complicated programs for solving large systems of equations. The idea behind MATLAB was to provide a simple way of using these programs that hid many of the complications. The idea was appealing to scientists who needed to use high performance software but had neither the time nor the inclination (nor in some cases the ability) to write it from scratch. Since its introduction, MATLAB has expanded to cover a very wide range of applications and can now be used as a very simple and transparent programming language where each line of code looks very much like the mathematical statement it is designed to implement. Basic MATLAB is good for the following.Computations, including linear algebra, data analysis, signal processing, polynomials and interpolation, numerical integration (quadrature), and numerical solution of deferential equations. Graphics, in 2-D and 3D, including colour, lighting, and animation. It also has collections of specialised functions, called toolboxes, that extend its functionality. In particular, it can do symbolic algebra, e.g. it can tell you that (x+y)^2 is equal to x^2+2*x*y+y^2. It is important not to confuse the type of programming that we shall do in this course with fundamental programming in an established high-level language like C, JAVA or FORTRAN. In this course we will take advantage of many of the built-in features of MATLAB to do quite complicated tasks but, in contrast to programming in a conventional high-level language, we shall have relatively little control over exactly how the instructions which we write are carried out on the machine. As a result, MATLAB programs for complicated tasks may be somewhat slower to run than programs written in languages such as C. However the MATLAB programs are very easy to write, a fact which we shall emphasise here. We shall use MATLAB as a vehicle for learning elementary programming skills and applications. These are skills which will be useful independently of the language you choose to work in. Some students in First Year will already know some of these skills, but we shall not assume any prior knowledge

Scope of MATLAB: Aerospace and Defense Automotive Biotech, Medical, and Pharmaceutical Chemical and Petroleum Communications Computers and Office Equipment Education
4

www.thinnkware.com

Electronics and Semiconductor Financial Services Industrial Equipment and Machinery Instrumentation Utilities and Energy Starting MATLAB
On the Windows desktop, the installer usually creates a shortcut icon for starting MATLAB; double-clicking on this icon opens MATLAB desktop.

The MATLAB desktop is an integrated development environment for working with MATLAB suite of toolboxes, directories, and programs. We see in Fig. 1.1 that there are four panels, which represent: 1. Command Window 2.Current Directory 3.Workspace 4.Command History A particular window can be activated by clicking anywhere inside its borders.

Fig. 1.1 MATLAB Desktop (version 7.0, release 14) Desktop layout can be changed by following Desktop --> Desktop Layout from the main menu as shown in Fig. 1.2 (Default option gives Fig. 1.1). 5

www.thinnkware.com

Fig. 1.2 Changing Desktop Layout to History and Command Window option

Command Window
We type all our commands in this window at the prompt ( >> ) and press return to see the results of our operations. Type the command ver on the command prompt to get information about MATLAB version, license number, operating system on which MATLAB is running, JAVA support version, and all installed toolboxes. If MATLAB don't regard to your speed of reading and flush the entire output at once, just type more on before supplying command to see one screen of output at a time. Clicking the What's New button located on the desktop shortcuts toolbar, opens the release notes for release 14 of MATLAB in Help window. These general release notes give you a quick overview of what products have been updated for Release 14. Working with Command Window allows the user to use MATLAB as a versatile scientific calculator for doing online quick computing. Input information to be processed by the MATLAB commands can be entered in the form of numbers and arrays. As an example of a simple interactive calculation, suppose that you want to calculate the torque ( T ) acting on 0.1 kg mass ( m ) at swing of the pendulum of length ( l ) 0.2 m. For small 6

www.thinnkware.com

values of swing, T is given by the formula window by typing: >> torque = 0.1*9.8*0.2*pi/6 MATLAB responds to this command by: torque = 0.1026

. This can be done in the MATLAB command

MATLAB calculates and stores the answer in a variable torque (in fact, a array) as soon as is predefined the Enter key is pressed. The variable torque can be used in further calculations. in MATLAB; so we can just use pi without declaring it to be 3.14.Command window indicating these operations is shown in Fig. 1.3.

Fig. 1.3 Command Window for quick scientific calculations ( text in colored boxes corresponds to explanatory notes ). If any statement is followed by a semicolon, >> m = 0.1; >> l = 0.2; >> g = 9.8;

www.thinnkware.com

the display of the result is suppressed. The assignment of the variable has been carried out even though the display is suppressed by the semicolon. To view the assignment of a variable, simply type the variable name and hit Enter. For example: >> torque=m*g*l*pi/6; >> torque torque = 0.1026 It is often the case that your MATLAB sessions will include intermediate calculations whose display is of little interest. Output display management has the added benefit of increasing the execution speed of the calculations, since displaying screen output takes time. Variable names begin with a letter and are followed by any number of letters or numbers (including underscore). Keep the name length to 31 characters, since MATLAB remembers only the first 31 characters. Generally we do not use extremely long variable names even though they may be legal MATLAB names. Since MATLAB is case sensitive, the variables A and a are different. When a statement being entered is too long for one line, use three periods, , followed by indicate that the statement continues on the next line. >> x=3-4*j+10/pi+5.678+7.890+2^2-1.89 >> x=3-4*j+10/pi+5.678... +7.890+2^2-1.89 + addition, subtraction, * multiplication, / division, and ^ power are usual arithmetic operators. to

The basic MATLAB trigonometric commands are sin, cos, tan, cot, sec and csc. The inverses , etc., are calculated by asin, acos, etc. The same is true for hyperbolic functions. Variables j = complex numbers. and i = are predefined in MATLAB and are used to represent

MATLAB representation of complex number or

The later case is always interpreted as a complex number, whereas, the former case is a complex number in MATLAB only if j has not been assigned any prior local value. MATLAB representation of complex number :

www.thinnkware.com

or or In Cartesian form, arithmetic additions on complex numbers are as simple as with real numbers. Consider two complex numbers by and . Their sum is given

For example, two complex numbers >> z1=3+4j; >> z2=1.8+2j; >> z=z1+z2 z= 4.8000 + 6.0000i

and

can be added in MATLAB as:

Multiplication of two or more complex numbers is easier in polar/complex exponential form. Two complex numbers with radial lengths rad. We change and are given with angles rad= and

to radians to give is given by

rad. The complex

exponential form of their product

This can be done in MATLAB by: >> theta1=(35/180)*pi; >> z1=2*exp(theta1*j); >> z2=2.5*exp(0.25*pi*j); >> z=z1*z2 z= 0.8682 - 4.9240j 9

www.thinnkware.com

Magnitude and phase of a complex number can be calculated in MATLAB by commands abs and angle. The following MATLAB session shows the magnitude and phase calculation of complex numbers and .

>> abs(5*exp(0.19*pi*j)) ans = 5 >> angle(5*exp(0.19*pi*j)) ans = 0.5969 >> abs(1/(2+sqrt(3)*j)) ans = 0.3780 >> angle(1/(2+sqrt(3)*j)) ans = -0.7137 The mathematical quantities log(x), respectively. and are calculated with exp(x), log10(x), and

All computations in MATLAB are performed in double precision . The screen output can be displayed in several formats. The default output format contains four digits past the decimal point for nonintegers. This can be changed by using the format command. Remember that the format command affects only how numbers are displayed, not how MATLAB computes or saves them. See how MATLAB prints in different formats.

Format command at MATLAB prompt format short format short e format long

Display format 31.4159 3.1416e+001 31.41592653589793 10

www.thinnkware.com

format long e format short g format long g format bank

3.141592653589793e+001 31.416 31.4159265358979 31.42

The following exercise will enable the readers to quickly write various mathematical formulas, interpreting error messages, and syntax related issues.

Exercise M1.1

i.

By using arbitrary values of

, check that

ii.

Verify with a few arbitrary values of .

that

iii.

Verify with a few arbitrary values of

that

. iv. For t =0, 2, 5, 7, 12 and 25, find the value of the function .

Exercise M1.2 1. Try entering complex number check the answer. Initialize in MATLAB as 3+j4 and and then enter 3+4j, 3+j*4, and

3+4*j and check the various answers. Interpret messages given by MATLAB. 2. Calculate magnitude and phase of the following complex numbers 11

www.thinnkware.com

for

using MATLAB.

a.

b.

3. Use MATLAB to calculate the magnitude and phase of for

Exercise M1.3

1. Calculate the quantity 2. Calculate for

for .

Note: Inf, and NaN are predefined in MATLAB. NaN stands for Not-aNumber and results from undefined operations like 0/0. Inf represents .

12

www.thinnkware.com

Current Directory Window


This window (Fig. 1.4) shows the directory, and files within the directory which are in use currently in MATLAB session to run or save our program or data. The default directory is C:\MATLAB7\work'. We can change this directory to the desired one by clicking on the square browser button near the pull-down window.

Fig. 1.4 Current directory window One can also use command line options to deal with directory and file related issues. Some useful commands are shown in Table 1.1.

13

www.thinnkware.com

Command cd, pwd cd .. cd \ cd dir_name ls or dir what mkdir (parentdir,dir_name) mkdir dir_name To see the current directory

Usage To go one directory back from the current directory To go back to the root directory To change to the directory named dir_name To see the list of files and subdirectories within the current directory Lists MATLAB-specific files in the directory. MATLAB specific files are with the extensions .m, .mat, .mdl, .mex, and .p. Makes new directory with the name dir_name in the parent directory specified by parentdir . When supplied with only dir_name, it creates new directory within the current directory

delete file_name delete *.m

Deletes file from the current directory. Deletes all m-files from the current directory.

MATLAB desktop snapshot showing selected commands from Table 1.1 are shown in Fig. 1.5.

Workspace
Workspace window shows the name, size, bytes occupied, and class of any variable defined in the MATLAB environment. For example in Fig.1.6, b' is 1 X 4 size array of data type double and thus occupies 32 bytes of memory. Double-clicking on the name of the variable opens the array editor (Fig. 1.7). We can change the format of the data (e.g., from integer to floating point), size of the array (for example, for variable A, from 3 X 4 array to 4 X 4 array) and can also modify the contents of the array.

14

www.thinnkware.com

Fig. 1.5 Example directory related commands If we right-click on the name of a variable, a menu pops up, which shows various operations for the selected variable, such as: open the array editor, save selected variable for future usage, copy, duplicate, and delete the variable, rename the variable, editing the variable, and various plotting options for the selected variable.

Fig. 1.6 Entries in the Workspace

15

www.thinnkware.com

Fig. 1.7 Array editor window Workspace related commands are listed in Table 1.2. Table 1.2 Usage Lists variables currently in the workspace Lists more information about each variable including size, bytes stored in the computer, and class type of the variables Clears the workspace. All variables are removed Removes all variables and functions from the workspace. This can also be done by selecting Edit from the main menu bar and then clicking the option Clear Workspace . Removes only var1 and var2 from the workspace.

Command who whos clear clear all clear var1 var2

For example, see the following MATLAB session for the use of who and whos commands. >> who Your variables are: Ab >> whos

16

www.thinnkware.com

Name Size Bytes Class double A 3x4 96 array double b 1x4 32 array Grand total is 16 elements using 128 bytes

Command History Window


This window (Fig. 1.8) contains a record of all the commands that we type in the command window. By double-clicking on any command, we can execute it again. It stores commands from one MATLAB session to another, hierarchically arranged in date and time. Commands remain in the list until they are deleted.

Fig. 1.8 Command history window Commands can also be recalled with the up-arrow commands. key. This helps in editing previous

Selecting one or more commands and right-clicking them, pops up a menu, allowing users to perform various operations such as copy, evaluate, or delete, on the selected set of commands. For example, two commands are being deleted in Fig. 1.9.

17

www.thinnkware.com

Getting Help
MATLAB provides hundreds of built-in functions covering various scientific and engineering computations. With numerous built-in functions, it is important to know how to look for functions and how to learn to use them. For those who want to look around and get a feel for the MATLAB computing environment by clicking and navigating through what catches their attention, a windowbased help is a good option. To activate the Help window, type helpwin or helpdesk on command prompt or start the Help Browser (Fig. 1.10) by clicking the icon from the desktop toolbar.

Fig. 1.9 Command history window with two commands being deleted

If you know the exact name of a command, type help commandname to get detailed task-oriented help. For example, type help helpwin in the command window to get the help on the command helpwin . If you don't know the exact command, but (atleast !) know the keyword related to the task you want to perform, the lookfor command may assist you in tracking the exact command. The help command searches for an exact command name matching the keyword, whereas the lookfor command searches for quick summary information in each command related to the keyword. For example, suppose that you were looking for a command to take the inverse of a matrix. MATLAB 18

www.thinnkware.com

does not have a command named inverse; so the command help inverse will not work. In your MATLAB command window try typing lookfor inverse to see the various commands available for the keyword inverse. MATLAB has a wonderful demonstration program that shows its various features through interactive graphical user interface. Type demo at the MATLAB prompt to invoke the demonstration program (Fig. 1.11) and the program will guide you throughout the tutorials.

Fig. 1.10 Help browser

Fig. 1.11 Demonstration Window 19

www.thinnkware.com

Elementary Matrices:
Basic data element of MATLAB is a matrix that does not require dimensioning. To create the matrix variable in MATLAB workspace, type the statement (note that any operation that assigns a value to a variable, creates the variable, or overwrites its current value if it already exists).

>> A=[8 1 6 2;3 5 7 4;4 9 2 6] The blank spaces (or commas) around the elements of the matrix rows separate the elements. Semicolons separate the rows. For the above statement, MATLAB responds with the display A= 8 3 4 1 5 9 6 7 2 2 4 6

Vectors are special class of matrices with a single row or column. To create a column vector variable in MATLAB workspace, type the statement >> b=[1; 1; 2; 3] b= 1 1 2 3 To enter a row vector, separate the elements by a space or comma ' , '. For example:
20

www.thinnkware.com

>> b=[1,1,2,3] b= 1 1 2 3

We can determine the size of the matrices (number of rows, number of columns) by using the size command. >> size(A) ans = 3 4 The command size, when used with the scalar option, returns the length of the dimension specified by the scalar. For example, size (A,1) returns the number of rows of A and size(A,2) returns the number of columns of A. >> size(A,1) ans = 3 >> size(A,2) ans = 4 For matrices, the length command returns either number of rows or number of columns, whichever is larger. For example, >> length(A)
21

www.thinnkware.com

ans = 4 For vectors, length command can be used to determine its number of elements. >> length(b) ans = 4 The use of colon ( : ) operator plays an important role in MATLAB. This operator may be used to generate a row vector containing the numbers from a given starting value xi, to the final value xf, with a specified increment dx, e.g., x=[xi:dx:xf] >> x=[0:0.1:1] x= Columns 1 through 7 0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000

Columns 8 through 11 0.7000 0.8000 0.9000 1.0000

By default, the increment is taken as unity. To generate linearly equally spaced samples between x1 and x2, use the command linspace(x1,x2) . By default, 100 samples will be generated. The command linspace (x1,x2, N) allows the control over number of samples to be generated. See the example below.
22

www.thinnkware.com

>> x=linspace(0,1,11) x= Columns 1 through 6 0 0.1000 0.2000 0.3000 0.4000 0.5000

Columns 7 through 11 0.6000 0.7000 0.8000 0.9000 1.0000

Learn how to generate logarithmically spaced vector using the command logspace . The colon operator can also be used to subscript matrices. For example, A(:,j) is the jth column of A, and A(i,:) is the ith row of A. Observe the following MATLAB session. >> A=[8 1 6 2;3 5 7 4;4 9 2 6]; >> A(2,:) ans = 3 5 7 4

>> A(3,2:4) ans = 9 2 6

>> A(1,3) ans =


23

www.thinnkware.com

6 >> B=A(1:3,2:3) B= 1 5 9 6 7 2

>> A(:,3)=[ ] A= 8 3 4 1 5 9 2 4 6

Manipulating matrices is almost as easy as creating them. Try the following operations: >> A+3 >> A-3 >> A*3 >> A/3

24

www.thinnkware.com

When you add/subtract/multiply/divide a vector/matrix by a number (or by a variable with a number assigned to it), MATLAB assumes that all elements of vector/matrix should be individually operated on. Table 1.3 provides the list of basic operations on any two arbitrary matrices A and B and their dimensional requirements. Table 1.3 Basic matrix operations
Operation Plus Minus Multiply Multiply (element-byelement) Divide (element-byelement) Divide (element-byelement) Matrix power Matrix power (element-byelement) Operator Example + A+B A-B * .* A*B A.*B Notes Must be of same dimensions Must be of same dimensions Must be of compatible dimensions Must be of same dimensions; multiplies element aij with element bij Must be of same dimensions; divides element aij by element bij Must be of same dimensions; divides element bij by element aij k must be a constant, A must be a square matrix k is a constant, A can be of any dimensions; gives (aij)k

./

A./B

.\ ^ .^

A.\B A^k A.^k

Exercise 1.4 Consider three matrices A, B, and C given below. Perform the following operations: A+B, B-C, A*C, A.*B, A./C, A.\B, A./B, (B*C)^3, and C.^3. Countercheck MATLAB answers manually. Try to interpret errors, if any.

25

www.thinnkware.com

Exercise 1.5 Create a vector t with 10 elements 1,2,.,10. Calculate for and ,

where Exercise 1.6

Create a vector t with initial time Calculate i. ii.

and final time

with an interval of 0.05.

M-file Editor:
Type edit on MATLAB prompt and hit enter (or follow File main menu bar or click on New M-File option from the icon in main toolbar). An Editor/Debugger window will open.

This is where you write, edit, create, can run from, and save your own programs (user created script files with sequences of MATLAB commands) in files called M - files . An example M-file is shown in Fig. M1.19. Create the same file in your MATLAB editor and then use the option File Save or File Save

As to save the file with the name decayed_sin.m in current working directory. You can save all files into your personalized directory. If your personal directory is immediately below the directory in which the MATLAB application program is installed ( e.g. , c:\MATLAB7p0), then all user written files are automatically accessible to MATLAB. If you want to store files somewhere else, then you need to specify the path to the files using the path or addpath command, or change the current working directory to the desired directory before you run the program. For example, your script file is in the directory my_dir, which is not the current working directory of the MATLAB. If the location of my_dir is ? c:\docume~1\control\ my_dir ', it can be included in the MATLAB search path by: >> path(path, ?c:\docume~1\control\my_dir'); or 26

www.thinnkware.com

>> addpath ?c:\docume~1\control\my_dir'; to remove specified directory from the MATLAB search path, use the command rmpath . Learn more about MATLAB search path through online help. Type simply the name of the file decayed_sin to execute it from the command window. Script can also be saved and executed simultaneously by clicking the icon in the main toolbar.

To open the existing M-file from the MATLAB command window, type edit filename (or follow File Open option from the main menu bar or click on icon in the main toolbar).

All variables created during the runtime of the script file are left in the workspace. Using who or whos , you can get information about them, and also access them by workspace window

Fig. 2.1 Example M-file

27

www.thinnkware.com

Scripts and Functions:


Overview
The MATLAB product provides a powerful programming language, as well as an interactive computational environment. You can enter commands from the language one at a time at the MATLAB command line, or you can write a series of commands to a file that you then execute as you would any MATLAB function. Use the MATLAB Editor or any other text editor to create your own function files. Call these functions as you would any other MATLAB function or command. There are two kinds of program files:

Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace. Functions, which can accept input arguments and return output arguments. Internal variables are local to the function.

If you are a new MATLAB programmer, just create the program files that you want to try out in the current folder. As you develop more of your own files, you will want to organize them into other folders and personal toolboxes that you can add to your MATLAB search path. If you duplicate function names, MATLAB executes the one that occurs first in the search path. To view the contents of a program file, for example, myfunction.m, use
type myfunction

Scripts
When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not return output arguments, any variables that they create remain in the workspace, to be used in subsequent computations. In addition, scripts can produce graphical output using functions like plot. For example, create a file called magicrank.m that contains these MATLAB commands: % Investigate the rank of magic squares r = zeros(1,32); for n = 3:32 r(n) = rank(magic(n)); end r bar(r) Typing the statement magicrank 28

www.thinnkware.com

causes MATLAB to execute the commands, compute the rank of the first 30 magic squares, and plot a bar graph of the result. After execution of the file is complete, the variables n and r remain in the workspace.

Functions
Functions are files that can accept input arguments and return output arguments. The names of the file and of the function should be the same. Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt. A good example is provided by rank. The file rank.m is available in the folder toolbox/matlab/matfun You can see the file with type rank Here is the file: function r = rank(A,tol) % RANK Matrix rank. % RANK(A) provides an estimate of the number of linearly % independent rows or columns of a matrix A. % RANK(A,tol) is the number of singular values of A % that are larger than tol. % RANK(A) uses the default tol = max(size(A)) * norm(A) * eps. s = svd(A); if nargin==1 tol = max(size(A)') * max(s) * eps; end r = sum(s > tol); 29

www.thinnkware.com

The first line of a function starts with the keyword function It gives the function name and order of arguments. In this case, there are up to two input arguments and one output argument. The next several lines, up to the first blank or executable line, are comment lines that provide the help text. These lines are printed when you type help rank The first line of the help text is the H1 line, which MATLAB displays when you use the lookfor command or request help on a folder. The rest of the file is the executable MATLAB code defining the function. The variable s introduced in the body of the function, as well as the variables on the first line, r, A and tol, are all local to the function; they are separate from any variables in the MATLAB workspace. This example illustrates one aspect of MATLAB functions that is not ordinarily found in other programming languagesa variable number of arguments. The rank function can be used in several different ways: rank(A) r = rank(A) r = rank(A,1.e-6) Many functions work this way. If no output argument is supplied, the result is stored in ans. If the second input argument is not supplied, the function computes a default value. Within the body of the function, two quantities named nargin and nargout are available that tell you the number of input and output arguments involved in each particular use of the function. The rank function uses nargin, but does not need to use nargout.

Types of Functions
MATLAB offers several different types of functions to use in your programming. Anonymous Functions An anonymous function is a simple form of the MATLAB function that is defined within a single MATLAB statement. It consists of a single MATLAB expression and any number of input and output arguments. You can define an anonymous function right at the MATLAB command line, or within a function or script. This gives you a quick means of creating simple functions without having to create a file for them each time. The syntax for creating an anonymous function from an expression is f = @(arglist)expression The statement below creates an anonymous function that finds the square of a number. When you call this function, MATLAB assigns the value you pass in to variable x, and then uses x in the equation x.^2: sqr = @(x) x.^2; 30

www.thinnkware.com

To execute the sqr function defined above, type a = sqr(5) a= 25 Primary and Subfunctions Any function that is not anonymous must be defined within a file. Each such function file contains a required primary function that appears first, and any number of subfunctions that may follow the primary. Primary functions have a wider scope than subfunctions. That is, primary functions can be called from outside of the file that defines them (e.g., from the MATLAB command line or from functions in other files) while subfunctions cannot. Subfunctions are visible only to the primary function and other subfunctions within their own file. The rank function shown in the section on functions is an example of a primary function. Private Functions A private function is a type of primary function. Its unique characteristic is that it is visible only to a limited group of other functions. This type of function can be useful if you want to limit access to a function, or when you choose not to expose the implementation of a function. Private functions reside in subfolders with the special name private. They are visible only to functions in the parent folder. For example, assume the folder newmath is on the MATLAB search path. A subfolder of newmath called private can contain functions that only the functions in newmath can call. Because private functions are invisible outside the parent folder, they can use the same names as functions in other folders. This is useful if you want to create your own version of a particular function while retaining the original in another folder. Because MATLAB looks for private functions before standard functions, it will find a private function named test.m before a nonprivate file named test.m. Nested Functions You can define functions within the body of another function. These are said to be nested within the outer function. A nested function contains any or all of the components of any other function. In this example, function B is nested in function A:
function x = A(p1, p2) ... B(p2) function y = B(p3) ... end ... end

Like other functions, a nested function has its own workspace where variables used by the function are stored. But it also has access to the workspaces of all functions in which it is nested. So, for example, a variable that has a value assigned to it by the primary function can be read or overwritten by a function nested at any level within the primary. Similarly, a variable that is 31

www.thinnkware.com

assigned in a nested function can be read or overwritten by any of the functions containing that function. Function Overloading Overloaded functions act the same way as overloaded functions in most computer languages. Overloaded functions are useful when you need to create a function that responds to different types of inputs accordingly. For instance, you might want one of your functions to accept both double-precision and integer input, but to handle each type somewhat differently. You can make this difference invisible to the user by creating two separate functions having the same name, and designating one to handle double types and one to handle integers. When you call the function, MATLAB chooses which file to dispatch to based on the type of the input arguments.

Global Variables
If you want more than one function to share a single copy of a variable, simply declare the variable as global in all the functions. Do the same thing at the command line if you want the base workspace to access the variable. The global declaration must occur before the variable is actually used in a function. Although it is not required, using capital letters for the names of global variables helps distinguish them from other variables. For example, create a new function in a file called falling.m: function h = falling(t) global GRAVITY h = 1/2*GRAVITY*t.^2; Then interactively enter the statements global GRAVITY GRAVITY = 32; y = falling((0:.1:5)'); The two global statements make the value assigned to GRAVITY at the command prompt available inside the function. You can then modify GRAVITY interactively and obtain new solutions without editing any files.

Passing String Arguments to Functions


You can write MATLAB functions that accept string arguments without the parentheses and quotes. That is, MATLAB interprets foo a b c as foo('a','b','c') However, when you use the unquoted form, MATLAB cannot return output arguments. For example,
legend apples oranges

32

www.thinnkware.com

creates a legend on a plot using the strings apples and oranges as labels. If you want the legend command to return its output arguments, then you must use the quoted form: [legh,objh] = legend('apples','oranges'); In addition, you must use the quoted form if any of the arguments is not a string. Caution While the unquoted syntax is convenient, in some cases it can be used incorrectly without causing MATLAB to generate an error. Constructing String Arguments in Code The quoted form enables you to construct string arguments within the code. The following example processes multiple data files, August1.dat, August2.dat, and so on. It uses the function int2str, which converts an integer to a character, to build the filename: for d = 1:31 s = ['August' int2str(d) '.dat']; load(s) % Code to process the contents of the d-th file end

The eval Function


The eval function works with text variables to implement a powerful text macro facility. The expression or statement eval(s) uses the MATLAB interpreter to evaluate the expression or execute the statement contained in the text string s. The example of the previous section could also be done with the following code, although this would be somewhat less efficient because it involves the full interpreter, not just a function call: for d = 1:31 s = ['load August' int2str(d) '.dat']; eval(s) % Process the contents of the d-th file end

Function Handles
You can create a handle to any MATLAB function and then use that handle as a means of referencing the function. A function handle is typically passed in an argument list to other functions, which can then execute, or evaluate, the function using the handle. Construct a function handle in MATLAB using the at sign, @, before the function name. The following example creates a function handle for the sin function and assigns it to the variable fhandle: 33

www.thinnkware.com

fhandle = @sin; You can call a function by means of its handle in the same way that you would call the function using its name. The syntax is fhandle(arg1, arg2, ...); The function plot_fhandle, shown below, receives a function handle and data, generates y-axis data using the function handle, and plots it: function plot_fhandle(fhandle, data) plot(data, fhandle(data)) When you call plot_fhandle with a handle to the sin function and the argument shown below, the resulting evaluation produces a sine wave plot: plot_fhandle(@sin, -pi:0.01:pi)

Function Functions
A class of functions called "function functions" works with nonlinear functions of a scalar variable. That is, one function works on another function. The function functions include

Zero finding Optimization Quadrature Ordinary differential equations

MATLAB represents the nonlinear function by the file that defines it. For example, here is a simplified version of the function humps from the matlab/demos folder: function y = humps(x) y = 1./((x-.3).^2 + .01) + 1./((x-.9).^2 + .04) - 6; Evaluate this function at a set of points in the interval 0 x 1 with x = 0:.002:1; y = humps(x); Then plot the function with plot(x,y)

34

www.thinnkware.com

The graph shows that the function has a local minimum near x = 0.6. The function fminsearch finds the minimizer, the value of x where the function takes on this minimum. The first argument to fminsearch is a function handle to the function being minimized and the second argument is a rough guess at the location of the minimum: p = fminsearch(@humps,.5) p= 0.6370 To evaluate the function at the minimizer, humps(p)

ans = 11.2528 Numerical analysts use the terms quadrature and integration to distinguish between numerical approximation of definite integrals and numerical integration of ordinary differential equations. MATLAB quadrature routines are quad and quadl. The statement
Q = quadl(@humps,0,1)

computes the area under the curve in the graph and produces
Q= 29.8583

Finally, the graph shows that the function is never zero on this interval. So, if you search for a zero with
z = fzero(@humps,.5)

35

www.thinnkware.com

you will find one outside the interval


z= -0.1316

Vectorization
One way to make your MATLAB programs run faster is to vectorize the algorithms you use in constructing the programs. Where other programming languages might use for loops or DO loops, MATLAB can use vector or matrix operations. A simple example involves creating a table of logarithms:
x = .01; for k = 1:1001 y(k) = log10(x); x = x + .01; end

A vectorized version of the same code is


x = .01:.01:10; y = log10(x);

For more complicated code, vectorization options are not always so obvious.

Preallocation
If you cannot vectorize a piece of code, you can make your for loops go faster by preallocating any vectors or arrays in which output results are stored. For example, this code uses the function zeros to preallocate the vector created in the for loop. This makes the for loop execute significantly faster: r = zeros(32,1); for n = 1:32 r(n) = rank(magic(n)); end Without the preallocation in the previous example, the MATLAB interpreter enlarges the r vector by one element each time through the loop. Vector preallocation eliminates this step and results in faster execution.

Examples of scripts:
1. Script 1: 36

www.thinnkware.com

%% To study the script. % find out the total no of years for doubling the amount invested. format long invest=input('type the investment: '); r=0.05; % interest rate bal=invest; year=0; disp(' year ') while (bal<2*invest) bal=bal+r*bal; year=year+1; end disp([year]);

2. %% Plot bar graphs using script. r=zeros(1,32) for n=3:32 r(n)=rank(magic(n)); end bar(r)

User defined functions: function [y]=decaying_sin(t) t=input('time interval'); y=exp(-t/2).*sin(2*pi*t); plot(t,y,'r',t,y,'*'); grid on; xlabel('time t'); ylabel('exp decay y'); title('sinusoidal exp decay');

Calling user defined function disp('how are u folks') y = Thinnk3_decaying_sin; disp('great job')

37

www.thinnkware.com

Programming Flow statements:

38

www.thinnkware.com

39

www.thinnkware.com

The condition is a logical relation and the statements are executed repeatedly while the condition remains true. the statements are repeated. The condition is tested each time before

It must eventually become false after a finite

number of steps, or the program will never terminate. Example. Suppose we have invested some money in a fund which pays 5% (compound) interest per year, and we would like to know how long it takes for the value of the investment to double. Indeed we would like to obtain a statement of the account for each year until the balance is doubled. We cannot use a for loop in this case, because we do not know beforehand how long this will take, so we cannot assign a value for the number of iterations on entering the loop. Instead, we must use a while loop.
40

www.thinnkware.com

41

www.thinnkware.com

42

www.thinnkware.com

43

www.thinnkware.com

44

www.thinnkware.com

45

www.thinnkware.com

EXERCISES3.1

46

www.thinnkware.com

Introduction to Computer vision


About Vision Sensors:
Vision sensors are video cameras with integrated signal processing and imaging electronics. They are used in industrial inspection, quality control, and design and manufacturing diagnostic applications. They often include interfaces for programming and data output, and a variety of measurement and inspection functions. When specifying vision sensors, it is important to determine whether a monochrome or color sensor is needed. Monochrome vision sensors present the image in black and white, or grayscale. Color sensing vision sensors are able the read the spectrum range using varying combinations of different discrete colors. One common technique is sensing the red, green, and blue components (RGB) and combining them to create a wide spectrum of colors. Multiple chip color is available on some vision sensors. It is a method of capturing color in which multiple chips are each dedicated to capturing part of the color image, such as one color, and the results are combined to generate the full color image. They typically employ color separation devices such as beam splitters rather than having integral filters on the sensors. Important specifications to consider when searching for vision sensors include number of images stored and maximum inspection rate. The number of images stored represents captured images that can be stored into on-board memory or non-volatile storage. The maximum inspection rate is the maximum number of parts or process steps that can be inspected or evaluated per unit time. This is usually given in units of inspections per second. Other important parameters include horizontal resolution, maximum frame rate, shutter speed, sensitivity, and signal to noise ratio. Inspection functions include object detection, edge detection, image direction, alignment, object measurement, object position, bar or matrix code, optical character recognition (OCR), and color mark or color recognition. Imaging technology used in vision sensors includes CCD, CMOS, tube, and film. Charge Coupled Devices (CCD) use a light-sensitive material on a silicon chip to detect electrons excited by incoming light. They also contain integrated microcircuitry required to transfer the detected signal along a row of discrete picture elements (or pixels) and thereby scan an image very rapidly. CMOS image sensors operate at lower voltages than CCDs, reducing power consumption for portable applications. Analog and digital processing functions can be integrated readily onto the CMOS chip, reducing system package size and overall cost. In a tube camera, the image is formed on a fluorescent screen. It is then read by an electron beam in a raster scan pattern and converted to a voltage proportional to the image light intensity. With film technology the image is exposed onto photosensitive film, which is then developed to be played or stored. The shutter, a manual door that admits light to the film, typically controls exposure. Other parameters to consider when specifying vision sensors include performance features, physical features, lens mounting, shutter control, sensor specifications, dimensions, and operating environment parameters. Cameras Available: CCD Cameras: Charge coupled device (CCD) cameras contain light-sensitive silicon chips that detect electrons excited by incoming light. They also contain micro circuitry that transfers a detected signal along a row of discrete picture elements or pixels, scanning the image very rapidly. CCD cameras use twodimensional CCD arrays with many thousands of pixels. CMOS Cameras: Complementary metal oxide semiconductor (CMOS) cameras use image sensors that operate at lower voltages than charged coupled devices (CCDs), reducing power consumption for portable 47

www.thinnkware.com

applications. Each CMOS active pixel sensor cell has its own buffer amplifier, and can be addressed and read individually. High Speed Cameras: High speed cameras are designed for rapid image acquisition for scientific or industrial analysis of rapidly changing or moving processes. Low Light Cameras: Low light cameras are designed for low light applications. They contain sensors that are highly sensitive to light and reduce images to a series of lines. Video Cameras: Video cameras take continuous pictures and generate signals for display or recording. They capture images by breaking them down into a series of lines. This search form does not include consumer devices such as camcorders.

Image Processing
Images in MATLAB: MATLAB stores most images as two-dimensional arrays (i.e., matrices), in which each element of the matrix corresponds to a single pixel in the displayed image. (Pixel is derived from picture element and usually denotes a single dot on a computer display.) Image Coordinate Systems: They are of two types: 1. Pixel Co-ordinates 2. Spatial Co-ordinates

Pixel Co-ordinates:
In this coordinate system, the image is treated as a grid of discrete elements, ordered from top to bottom and left to right

48

www.thinnkware.com

For pixel coordinates, the first component r (the row) increases downward,while the second component c (the column) increases to the right. Pixel coordinates are integer values and range between 1 and the length of the row or column.

Spatial Co-ordinates:
In this spatial coordinate system, locations in an image are positions on a plane, and they are described in terms of x and y (not r and c as in the pixel coordinate system).

Facts: 1. The spatial coordinates of the center point of any pixel are identical to the pixel coordinates for that pixel. 2. In pixel coordinates, the upper left corner of an image is (1,1), while in spatial coordinates, this location by default is (0.5,0.5). This difference is due to the pixel coordinate systems being discrete, while the spatial coordinate system is continuous. Also, the upper left corner is always (1,1) in pixel coordinates, but you can specify a nondefault origin for the spatial coordinate system. 3. The order of the horizontal and vertical components is reversed in the notation for these two systems. As mentioned earlier, pixel coordinates are expressed as (r,c), while spatial coordinates are expressed as (x,y).

Image Types in the Toolbox:

Overview of Image Types

49

www.thinnkware.com

Binary Images In a binary image, each pixel assumes one of only two discrete values: 1 or 0. A binary image is stored as a logical array. By convention, this documentation uses the variable name BW to refer to binary images.

50

www.thinnkware.com

Indexed Images An indexed image consists of an array and a colormap matrix. The pixel values in the array are direct indices into a colormap. By convention, this documentation uses the variable name X to refer to the array and map to refer to the colormap. The colormap matrix is an m-by-3 array of class double containing floating-point values in the range [0,1]. Each row of map specifies the red, green, and blue components of a single color. An indexed image uses direct mapping of pixel values to colormap values. The color of each image pixel is determined by using the corresponding value of X as an index into map. A colormap is often stored with an indexed image and is automatically loaded with the image when you use the imread function.After you read the image and the colormap into the MATLAB workspace as separate variables, you must keep track of the association between the image and colormap. However, you are not limited to using the default colormap--you can use any colormap that you choose. The relationship between the values in the image matrix and the colormap depends on the class of the image matrix. If the image matrix is of class single or double,it normally contains integer values 1 through p, where p is the length of the colormap. the value 1 points to the first row in the colormap, the value 2 points to the second row, and so on. If the image matrix is of class logical, uint8 or uint16, the value 0 points to the first row in the colormap, the value 1 points to the second row, and so on.

51

www.thinnkware.com

Grayscale Images A grayscale image (also called gray-scale, gray scale, or gray-level) is a data matrix whose values represent intensities within some range. MATLAB stores a grayscale image as a individual matrix, with each element of the matrix corresponding to one image pixel. By convention, this documentation uses the variable name I to refer to grayscale images. The matrix can be of class uint8, uint16, int16, single, or double.While grayscale images are rarely saved with a colormap, MATLAB uses a colormap to display them. For a matrix of class single or double, using the default grayscale colormap, the intensity 0 represents black and the intensity 1 represents white. For a matrix of type uint8, uint16, or int16, the intensity intmin(class(I)) represents black and the intensity intmax(class(I)) represents white.

52

www.thinnkware.com

Truecolor Images A truecolor image is an image in which each pixel is specified by three values one each for the red, blue, and green components of the pixel's color. MATLAB store truecolor images as an m-by-n-by-3 data array that defines red, green, and blue color components for each individual pixel. Truecolor images do not use a colormap. The color of each pixel is determined by the combination of the red, green, and blue intensities stored in each color plane at the pixel's location. Graphics file formats store truecolor images as 24-bit images, where the red, green, and blue components are 8 bits each. This yields a potential of 16 million colors. The precision with which a real-life image can be replicated has led to the commonly used term truecolor image. A truecolor array can be of class uint8, uint16, single, or double. In a truecolor array of class single or double, each color component is a value between 0 and 1. A pixel whose color components are (0,0,0) is displayed as black, and a pixel whose color components are (1,1,1) is displayed as white. The three color components for each pixel are stored along the third dimension of the data array. For example, the red, green, and blue color components of the pixel (10,5) are stored in RGB(10,5,1), RGB(10,5,2), and RGB(10,5,3), respectively.

53

www.thinnkware.com

To determine the color of the pixel at (2,3), you would look at the RGB triplet stored in (2,3,1:3). Suppose (2,3,1) contains the value 0.5176, (2,3,2) contains 0.1608, and (2,3,3) contains 0.0627. The color for the pixel at (2,3) is0.5176 0.1608 0.0627To further illustrate the concept of the three separate color planes used in a truecolor image, the code sample below creates a simple image containing uninterrupted areas of red, green, and blue, and then creates one image for each of its separate color planes (red, green, and blue).

Program: Write the program which displays each color plane image separately, and also displays the original image .RGB=reshape(ones(64,1)*reshape(jet(64),1,192),[64,64,3]); R=RGB(:,:,1); G=RGB(:,:,2); 54

www.thinnkware.com

B=RGB(:,:,3); imshow(R) figure, imshow(G) figure, imshow(B) figure, imshow(RGB) Ouput:

55

www.thinnkware.com

Converting Between Image Types:

Program: Write a program to convert the one type of image in to other.


i=imread('Red.jpg'); imfinfo('Red.jpg'); t=im2double(i) %gives various infomation about the image. %Convert image to double precision

h=rgb2hsv(i); %converts the RGB image into HSV image figure;imshow(h(:,:,1)); %displays the hue component of HSV image. figure;imshow(h(:,:,2)); %displays the saturation component of HSV image. figure;imshow(h(:,:,3)); %displays the intensity component of HSV image.

r=hsv2rgb(h); %converts the HSV image into RGB image figure;imshow(i(:,:,1)); % displays the red component of RGB image. figure;imshow(i(:,:,2)); % displays the green component of RGB image. figure;imshow(i(:,:,3)); % displays the blue component of RGB image.

g=rgb2gray(i); %converts the RGB image into Gray scale image figure;imshow(g);

56

www.thinnkware.com

You might also like