You are on page 1of 34

Chapter 1

INTRODUCTION
1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 What is MATLAB? Why Matrix The MATLAB System Starting MATLAB on Windows Platforms Quitting MATLAB MATLAB Windows Running Basic Command Scope of MATLAB

1.1 What Is MATLAB?


The name MATLAB stands for matrix laboratory. MATLAB was originally written to provide easy access to matrix software developed by the LINPACK and EISPACK projects. Today, MATLAB engines incorporate the LAPACK and BLAS libraries, embedding the state of the art in software for matrix computation. MATLAB has evolved over a period of years with input from many users. In university environments, it is the standard instructional tool for introductory and advanced courses in mathematics, engineering, and science. In industry, MATLAB is the tool of choice for high-productivity research, development, and analysis. MATLAB features a family of add-on application-specific solutions called toolboxes. Very important to most users of MATLAB, toolboxes allow you to learn and apply specialized technology. Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment to solve particular classes of problems. Areas in which toolboxes are available include signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and many others. MATLAB is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation. Typical uses include Math and computation Algorithm development Data acquisition Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including graphical user interface building

2.1 Why Matrix


MATLAB is an interactive system whose basic data element is an array that does not require dimensioning. This allows you to solve many technical computing problems, especially those with matrix and vector formulations, in a fraction of the time it would take to write a program in a scalar non-interactive language such as C or FORTRAN.

2.3 The MATLAB System


The MATLAB system consists of five main parts: Development Environment

Chapter 1: Introduction This is the set of tools and facilities that help you use MATLAB functions and files. Many of these tools are graphical user interfaces. It includes the MATLAB desktop and Command Window, a command history, an editor and debugger, and browsers for viewing help, the workspace, files, and the search path. The MATLAB Mathematical Function Library This is 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. The MATLAB Language This is a high-level matrix/array language with control flow statements, functions, data structures, input/output, and object-oriented programming features. It allows both "programming in the small" to rapidly create quick and dirty throw-away programs, and "programming in the large" to create large and complex application programs. Graphics MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. It includes high-level functions for twodimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. It also includes low-level functions that allow you to fully customize the appearance of graphics as well as to build complete graphical user interfaces on your MATLAB applications. The MATLAB External Interfaces (API) This is a library that allows you to write C and Fortran programs that interact with MATLAB. It includes facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files.

2.4 Starting MATLAB on Windows Platforms


To start MATLAB on a Microsoft Windows platform, select the Start -> Programs -> MATLAB 7.0.1 -> MATLAB 7.0.1, or double-click the MATLAB shortcut icon on your Windows desktop. The shortcut was automatically created when you installed MATLAB. If you have trouble starting MATLAB, see troubleshooting information in the Installation Guide for Windows.

2.5 Quitting MATLAB


To end your MATLAB session, select File -> Exit MATLAB in the desktop, or type quit in the Command Window. You can run a script file named finish.m each time MATLAB quits that, for example, executes functions to save the workspace, or displays a quit confirmation dialog box.

2.6 MATLAB Desktop


When you start MATLAB, the MATLAB desktop appears, containing tools (graphical user interfaces) for managing files, variables, and applications associated with MATLAB.
Courseware on MATLAB Workshop

Chapter 1: Introduction

Figure MATLAB Desktop The following illustration shows the default desktop. MATLAB has an extensive graphical user interface. When MATLAB starts, the MATLAB window will appear, with several subwindows and menu bars. All of MATLABs windows in the default desktop are docked, which means that they are tiled on the main MATLAB window. You can undock a window by selecting the menu item Desktop Undock or by clicking its undock button: Help window This window is the most useful window for beginning MATLAB users, and MATLAB experts continue to use it heavily. Select Help MATLAB Help or type doc. The Help window has most of the features you would see in any web browser (clickable links, a back button, and a search engine, for example). You can also use the help command, typed in the Command window. For example, the command help eig will give information about the eigen value function eig. You can also preview some of the features of MATLAB by first entering the command demo or by selecting Help Demos, and then selecting from the options offered. Start button The Start button in the bottom left corner of the MATLAB Desktop allows you to start up demos, tools, and other windows not present when you start MATLAB. Try Start: MATLAB: Demos and run one of the demos from the MATLAB Demo window. Command window

Courseware on MATLAB Workshop

Chapter 1: Introduction MATLAB expressions and statements are evaluated as you type them in the Command window, and results of the computation are displayed there too. Expressions and statements are also used in M-files. They are usually of the form: variable = expression or simply functions Expressions are usually composed from operators, functions, and variable names. Evaluation of the expression produces a matrix (or other data type), which is then displayed on the screen or assigned to a variable for future use. If the variable name and = sign are omitted, a variable ans (for answer) is automatically created to which the result is assigned. A statement is normally terminated at the end of the line. However, a statement can be continued to the next line with three periods (...) at the end of the line. Several statements can be placed on a single line separated by commas or semicolons. Click on the Workspace tab to bring up the Workspace window (it starts out underneath the Current Directory window in the default layout) so you can see a list of the variables you create, and type this command in the Command window: >>A = [1 2 3 ; 4 5 6 ; -1 7 9] or this one: >>A = [ 123 456 -1 7 9] in the Command window. Either one creates the obvious 3-by-3 matrix and assigns it to a variable A. Note: MATLAB is case-sensitive in the names of commands, functions, and variables, so A and a are two different variables. Note: If you want to use reuse previously used command on the command window, it is easier to hit the up arrow key until you see the command you want in the history of MATLAB, and then hit enter. You can clear the Command window with the { >>clc }command or with Edit Clear Command Window. Most numeric computations in MATLAB are done in double precision, which has about 16 digits of accuracy. The command format compact suppresses most blank lines, allowing more information to be placed on the screen or page. The command format loose returns to the non-compact format. These two commands are independent of the other format commands.

Courseware on MATLAB Workshop

Chapter 1: Introduction You can pause the output in the Command window with the { >>more on } command. Type { >>more off } to turn this feature off. Workspace window The Workspace window lists variables that you have either entered or computed in your MATLAB session. There are many fundamental data types (or classes) in MATLAB, each one a basically multidimensional array. An array of this type is called a matrix. A matrix with only one row or one column is called a vector (row vectors and column vectors behave differently; they are more than mere one-dimensional arrays). A 1-by-1 matrix is called a scalar. All the matrices and other variables that you create on the command prompt, are shown in your Workspace window. The command { >>who } or { >>whos } lists the variables currently in the workspace with their properties. A variable can be cleared from the workspace with the command { >>clear variablename } or by rightclicking the variable in the Workspace editor and selecting Delete. The command { >>clear } alone clears all variables from the workspace. Command History window This window lists all the commands used so far. You can re-execute a command from this window by double-clicking or dragging the command into the Command window. Array Editor Window Once an array exists, it can be modified with the Array Editor, which acts like a spreadsheet for matrices. Go to the Workspace window and double-click on the variable. The array editor window will gets opened where you can edit the variable and then go back to the Command window and type the name of variable. Note: You can also edit the variable by typing the command >>openvar('nameVariable') Current Directory window Your current directory is where MATLAB looks for your M-files, and for workspace (.mat) files that you load and save. You can use the menus and buttons in the Current Directory window to peruse your files. The command { >>pwd } returns the name of the current directory, and { >>cd } will change the current directory. The command { >>dir } lists the contents of the current working directory, whereas the command { >>what } lists only the MATLAB-specific files in the directory, and grouped by file type. The MATLAB commands { >>delete } and { >>type } can be used to delete a file and display a file in the Command window, respectively.

1.7 Running Basic Command


Matlab having many built-in Commands that display basic features doing basic things in the environment, some of them we have already discussed in this chapter.

Courseware on MATLAB Workshop

Chapter 1: Introduction Commands >>ver >>date >>pwd

1.8 Scope of MATLAB


MATLAB is one of powerful tool to test and verify algorithms and designs. Data can be effortlessly analyzed in the MATLAB environment In MATLAB one can view data in diversified ways like plots etc for visual representation. There are many toolboxes are made available to solve the problems of different domains like image processing, mathematics etc. With the help of Simulink one can create graphical block-diagram based system and simulate the same. One can create the rich GUI for their applications in the MATLAB.

Courseware on MATLAB Workshop

Chapter 2
MATLAB KNOW THE BASICS
2.1 Managing Variables 2.2 Accessing Array and Matrix 2.3 The Colon ( : ) Operator Creating Variables 2.4 Suppressing The Output 2.5 Diary 2.6 Storing the Variables and Workspace in MAT File 2.7 Sub-matrices and Colon

2.1 Managing Variables


The best way for you to get started with MATLAB is to learn how to handle matrices. Start MATLAB and follow along with each example. You can enter matrices into MATLAB in several different ways: Enter an explicit list of elements. Load matrices from external data files. Generate matrices using built-in functions. Create matrices with your own functions in M-files. Start by entering matrix as a list of its elements. You only have to follow a few basic conventions: Separate the elements of a row with blanks or commas. Use a semicolon, ; , to indicate the end of each row. Surround the entire list of elements with square brackets, [ ]. To enter matrix, simply type in the Command Window >>A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] MATLAB displays the matrix you just entered: A= 16 3 5 10 9 6 4 15

2 13 11 8 7 12 14 1

Once you have entered the matrix, it is automatically remembered in the MATLAB workspace. Deleting Rows and Columns You can delete rows and columns from a matrix using just a pair of square brackets. Start with >>X = A; Then, to delete the second column of X, use >>X(:,2) = []

Chapter 2: MATLAB Know the Basics

This changes X to X= 16 2 13 5 11 8 9 7 12 4 14 1 If you delete a single element from a matrix, the result is not a matrix anymore. So, expressions like >>X(1,2) = [] result in an error. However, using a single subscript deletes a single element, or sequence of elements, and reshapes the remaining elements into a row vector. So >>X(2:2:10) = [] results in X= 16

13

12

Deleting the variables With the help of { >>clear } one can delete the entire workspace, and also it is possible to delete the particular variable by referring its name in the command.

2.2 Accessing Array and Matrix


The element in row i and column j of A is denoted by A(i,j). For example, A(4,2) is the number in the fourth row and second column. For our magic square, A(4,2) is 15. So to compute the sum of the elements in the fourth column of A, type >>A(1,4) + A(2,4) + A(3,4) + A(4,4) This produces ans = 34 but is not the most elegant way of summing a single column. It is also possible to refer to the elements of a matrix with a single subscript, A(k). This is the usual way of referencing row and column vectors. But it can also apply to a fully two-dimensional matrix, in which case the array is regarded as one long column vector formed from the columns of the original matrix. So, for our magic square, A(8) is another way of referring to the value 15 stored in A(4,2). If you try to use the value of an element outside of the matrix, it is an error:

Courseware on MATLAB Workshop

Chapter 2: MATLAB Know the Basics >>t = A(4,5) Index exceeds matrix dimensions. On the other hand, if you store a value in an element outside of the matrix, the size increases to accommodate the newcomer: >>X = A; >>X(4,5) = 17 X= 16 3 5 10 9 6 4 15

2 13 11 8 7 12 14 1

0 0 0 17

Next, create a column vector, x, with: >>x = [4 5 6]' or equivalently >>x = [3 ; 2 ; 1] With this vector, x(3) denotes the third coordinate of vector x, with a value of 1. Higher dimensional arrays are similarly indexed. An array in the MATLAB accepts only positive integers as index. In an array index expression, end denotes the index of the last element. Try: x = rand(1,5) x = x(end:-1:1)

2.3 The Colon ( : ) Operator Creating Variables


The expression 1:5 is the row vector [1 2 3 4 5]. The numbers need not be integers, and the increment need not be one. For example, 0:0.2:1 gives [0 0.2 0.4 0.6 0.8 1] with an increment of 0.2 and 5:-1:1 gives [5 4 3 2 1] with an increment of -1. These vectors are commonly used in for loops, described in Section 6.1. Be careful how you mix the colon operator with other operators. Compare 1:5-3 with (1:5)-3. If you want specific control over how many terms are in the sequence, use linspace instead of the colon operator. The expression linspace(lo,hi) is identical to lo:inc:hi, except that inc is chosen so that the vector always has exactly 100 entries (even if lo and hi are equal). The last entry in the sequence is always hi. To generate a sequence with n terms instead of the default of 100, use linspace(lo,hi,n). Compare linspace(1,5.1,5) with 1:5.1.

Courseware on MATLAB Workshop

Chapter 2: MATLAB Know the Basics

2.4 Suppressing the Output


If the last character of a statement is a semicolon, display of the result is suppressed, but the assignment is carried out. This is essential in suppressing unwanted display of intermediate results.

2.5 Diary
You can save the Command window dialog with the diary command: diary filename This causes what appears subsequently in the Command window to be written to the named file (if the filename is omitted, it is written to a default file named diary) until you type the command diary off; the command diary on causes writing to the file to resume. When finished, you can edit the file as desired and print it out. For hard copy of graphics

2.6 Storing the Variables and Workspace in MAT File


When you log out or exit MATLAB, all variables are lost. The command save before exiting causes all variables to be written to a file named matlab.mat in the current working directory. The command load will restore the workspace to its former state. Commands save and load takes file names and variable names as optional arguments.

2.8 Sub-matrices and Colon


Vectors and sub-matrices are often used in MATLAB to achieve fairly complex data manipulation effects. Colon notation (which is used to both generate vectors and reference sub-matrices) and subscripting by integral vectors are keys to efficient manipulation of these objects. Creative use of these features minimizes the use of loops (which can slow MATLAB) and makes code simple and readable. Special effort should be made to become familiar with them. Accessing sub-matrices Colon notation can be used to access sub-matrices of a matrix. To try this out, first type the two commands: >>A = rand(6,6) >>B = rand(6,4) which generate a random 6-by-6 matrix A and a random 6-by-4 matrix B. A(1:4,3) is the column vector consisting of the first four entries of the third column of A. A colon by itself denotes an entire row or column: A(:,3) is the third column of A, and A(1:4,:) is the first four rows. Arbitrary integral vectors can be used as subscripts: A(:,[2 4]) contains as columns, columns 2 and 4 of A. Such subscripting can be used on both sides of an assignment statement:

10

Courseware on MATLAB Workshop

Chapter 2: MATLAB Know the Basics

>>A(:,[2 4 5]) = B(:,1:3) replaces columns 2,4,5 of A with the first three columns of B. Try it. Note that the entire altered matrix A is displayed and assigned. In this way one can create a sub-matrix from any matrix in simple single statement.

11

Courseware on MATLAB Workshop

Chapter 3
MANIPULATING VARIABLES IN MATLAB
3.1 Matrix Operators 3.2 Element-Wise Operators 3.3 Relational Operators and Logical Operators 3.4 Other Data Types 3.5 Basic Built-In Functions

3.1 Matrix operators


The following matrix operators are available in the MATLAB: + * ^ ' .' \ / addition or unary plus subtraction or negation multiplication power transpose (real) or conjugate transpose (complex) transpose (real or complex) left division (backslash or mldivide) right division (slash or mrdivide)

matrix A by adding one to each of its elements: >>A = A + 1 These matrix operators apply, of course, to scalars (1 x 1 matrices) as well. If the sizes of the matrices are incompatible for the matrix operation, an error message will result, except in the case of scalar-matrix operations (for addition, subtraction, division, and multiplication, in which case each entry of the matrix is operated on by the scalar, as in A=A+1). Matrix division (slash and backslash operators) The matrix division operations deserve special comment. These are also called the backslash (\) and slash operators (/); they are also referred to as the mldivide and mrdivide functions. If A is square and non-singular, then A\b and b/A are mathematically the same as inv(A)*b and b*inv(A), respectively, where inv(A) computes the inverse of A.

3.2 Element-Wise Operators


Matrix addition and subtraction already operate element-wise, but the other matrix operations do not. These other operators (*, ^, \, and /) can be made to operate element-wise by preceding them by a period ( . ). For example, >>[1 2 3 4] .* [1 2 3 4] >>[1 2 3 4] .^ 2

Chapter 3: Manipulating Variables in MATLAB

will yield [1 4 9 16]. Note: Also try A^2 with A . ^ 2.

3.3 Relational Operators and Logical Operators


The relational operators of MATLAB are: < > <= >= == ~= less than greater than less than or equal greater than or equal equal not equal

They all operate entry-wise. Note that = is used in an assignment statement whereas == is a relational operator. Relational operators may be connected by logical operators: & | ~ && || and or not short-circuit and short-circuit or

The result of a relational operator is of type logical, and is either true (one) or false (zero). Thus, ~0 is 1, ~3 is 0, and 4 & 5 is 1, for example. When applied to scalars, the result is a scalar. Try entering 3 < 5, 3 > 5, 3 == 5, and 3 == 3. When applied to matrices of the same size, the result is a matrix of ones and zeros giving the value of the expression between corresponding entries. You can also compare elements of a matrix with a scalar. Test: >>A = [1 2 ; 3 4] >>A >= 2 >>B = [1 3 ; 4 2] >>A < B The short-circuit operator && acts just like its non-shortcircuited counterpart (&), except that it evaluates its left expression first, and does not evaluate the right expression if the first expression is false. This is useful for partially-defined functions. Suppose f(x) returns a logical value but generates an error if x is zero. The expression (x~=0) && f(x) returns false if x is zero, without calling f(x) at all. The short-circuit or (||) acts similarly. It does not evaluate the right expression if the left is true. Both

13

Courseware on MATLAB Workshop

Chapter 3: Manipulating Variables in MATLAB && and || require their operands to be scalar and convertible to logical, while & and | can operate on arrays.

3.4 Other data types


MATLAB supports many other data types, including logical variables, integers of various sizes, single-precision floating-point variables, sparse matrices, multidimensional arrays, cell arrays, and structures. In the MATLAB the default data type is double, a 64-bit IEEE floating-point number. The single type is a 32-bit IEEE floating-point number which should be used only if you are desperate for memory. A double can represent integers in the range -253 to 253 without any round-off error, Integer types are only needed in special cases such as signal processing, image processing, encryption, and bit string manipulation. Integers come in signed and unsigned flavors, and in sizes of 8, 16, 32, and 64 bits. Integer arithmetic is not modular, but saturates on overflow. Cell arrays are collections of other arrays or variables of varying types and are formed using curly braces. For example, >>c = {[3 2 1] ,'I love MATLAB'} creates a cell array. The expression c{1} is a row vector of length 3, while c{2} is a string. A struct is variable with one or more parts, each of which has its own type. Try, for example, >>x.particle = 'electron' >>x.position = [2 0 3] >>x.spin = 'up' The variable x describes an object with several characteristics, each with its own type.

3.5 Basic Built-In Functions


MATLAB has a large number of built-in functions. You have already seen some of them. This section describes the some of common functions. Constructing matrices Convenient matrix building functions include: eye zeros ones diag rand identity matrix matrix of zeros matrix of ones create or extract diagonals randomly generated matrix
Courseware on MATLAB Workshop

14

Chapter 3: Manipulating Variables in MATLAB magic magic square The command rand(n) creates an n-by-n matrix with randomly generated entries distributed uniformly between 0 and 1 while rand(m,n) creates an m-by-n matrix (m and n are non-negative integers). Try: >>A = rand(3) If x is a vector, diag(x) is the diagonal matrix with x down the diagonal; if A is a matrix, then diag(A) is a vector consisting of the diagonal of A. Try: >>x = 1:3 >>diag(x) >>diag(A) magic(n) creates an n-by-n matrix that is a magic square (rows, columns, and diagonals have common sum) Scalar functions Certain MATLAB functions operate essentially on scalars but operate entry-wise when applied to a vector or matrix. Some of the most common such functions are: abs ceil floor rem sqrt acos cos log round tan asin exp log10 sign atan fix mod sin The following statements will generate a sine table: >>x = (0:0.1:2)' >>y = sin(x) >>plot(x y) Note It produces a vector y from the vector x.

15

Courseware on MATLAB Workshop

Chapter 3: Manipulating Variables in MATLAB Vector functions Most of these functions perform basic statistical computations The primary functions are: max sum median min mean The maximum entry in a matrix A is given by max(A), if A is a row vector. MATLAB functions may have single or multiple output arguments. Square brackets are used to the left of the equal sign to list the outputs. For example, >>[m n] = size(A) produces a column vector containing the count of row and column of a matrix The find function The find function is unlike the other matrix and vector functions. find(x), where x is a vector, returns an array of indices of nonzero entries in x. This is often used in conjunction with relational operators. Suppose you want a vector y that consists of all the values in x greater than 1. >>x = 2*rand(1,5) >>y = x(find(x > 1)) With three output arguments, you get more information: >>A = rand(3) >>[i,j,x] = find(A) returns three vectors, with one entry in i, j, and x for each nonzero in A (row index, column index, and numerical value, respectively). With this matrix A, >>[i,j,x] = find(A > .5)

16

Courseware on MATLAB Workshop

Chapter 4
PROGRAMMING IN MATLAB THE M - FILES
4.1 Basic Parts of an M-File 4.2 Branching 4.3 Loops 4.4 Breaking from a Loop 4.5 Structure of Function M-files

MATLAB provides a full programming language that enables you to write a series of MATLAB statements into a file and then execute them with a single command. You write your program in an ordinary text file, giving the file a name of filename.m. The term you use for filename becomes the new command that MATLAB associates with the program. The file extension of .m makes this a MATLAB M-file. This section covers Types of M-Files Basic Parts of an M-File Creating a Simple MFile. M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that also accept input arguments and produce output. MATLAB scripts: Are useful for automating a series of steps you need to perform many times. Do not accept input arguments or return output arguments. Store variables in a workspace that is shared with other scripts and with the MATLAB command line interface.

4.1 Basic Parts of an M-File


This simple code shows the basic parts of an M-file. Note that any line that begins with % is not executable: % Compute a some value. % Help text Statement/commands/function

%end of file

Scripts can have any MATLAB Commands. Every time you create an M-file, you are writing a computer program using the MATLAB programming language. You can do quite a lot in MATLAB using no more than the most basic programming techniques that we have already introduced. Here techniques that is useful for attacking more complicated problems with MA TLAB. If

Chapter 4: Programming in MATLAB The M - Files you are already familiar with another programming language, much of this material will be quite easy for you to pick up!

4.2 Branching
In the M-file commands are executes the same sequence as they have written every condition. However, one often wants a function to perform a different sequence of commands in different cases, depending on the conditions. You can accomplish this with a branching command, and as in many other programming languages, branching in MATLAB is usually done with the command if, which we will discuss now. Branching with if For a simple illustration of branching with if, consider the following code M-file, which computes the absolute value of a real number: if x >= 0 y = x; else y = -x; end The first line of this M-file states that the function has a single input x and a single output y. If the input x is nonnegative, the if statement is determined by MATLAB to be true. Then the command between the if and the else statements is executed to set y equal to x, while MATLAB skips the command between the else and end statements. And in the opposite condition the opposite part will be executed. In general, if must be followed on the same line by an expression that MATLAB will test to be true or false. In between, there may be one or more elseif statements (see below) and/or an else statement (as above). Note: that MATLAB requires a double equal sign == to test for equality; a single equal sign is reserved for the assignment of values to variables. Logical Expressions In the examples above, we used relational operators suchas >=, >, and == to form a logical expression, and we instructed MATLAB to choose between different commands according to whether the expression is true or false. Type help relop to see all of the available relational operators. Some of these operators, suchas & (AND) and | (OR), can be used to form logical expressions that are more complicated than those that simply compare two numbers. For example, the expression(x > 0) | (y > 0) will be true if x or y (or both) is positive, and false if neither is positive. In this particular example, the parentheses are not necessary, but generally compound logical expressions like this are both easier to read and less prone to errors if parentheses are used to avoid ambiguities.

18

Courseware on MATLAB Workshop

Chapter 4: Programming in MATLAB The M - Files Branching with switch The other main branching command is switch. It allows you to branch among several cases just as easily as between two cases, though the cases must be described through equalities rather than inequalities. Here is a simple example, which distinguishes between three cases for the input: switch x case 1 y = one; case 2 y = two; otherwise y = many; end Here the switch statement evaluates the input x and then execution of the M-file skips to whichever case statement has the same value. Thus if the input x equals 1, then the output y is set to be the string one, while if x is 2, then y is set to two. In each case , once MATLAB encounters another case statement or since an otherwise statement, it skips to the end statement, so that at most one case is executed. If no match is found among the case statements, then MATLAB skips to the (optional) otherwise statement, or else to the end statement. In the example above, because of the otherwise statement, the output is many if the input is not 1 or 2.

4.3 Loops
Loop a sequence of commands to be executed multiple times. A loop specifies that a command or group of commands should be repeated several times. The easiest way to create a loop is to use a for statement. Here is a simple example that computes and displays 10! = 10 9 8 2 1: f = 1; for n = 2:10 f = f*n; end f The loop begins with the for statement and ends with the end statement. The command between those statements is executed a total of nine times, once for each value of n from 2 to 10. We used a semicolon to suppress intermediate output within the loop. While Loop When you use for, you effectively specify the number of times to run the loop in advance (though this number may depend for instance on the input to a function Mfile). Sometimes you may want to keep running the commands in a loop until a certain condition is met, without deciding in advance on the number of iterations. In MATLAB, the command that allows you to do so is while.

19

Courseware on MATLAB Workshop

Chapter 4: Programming in MATLAB The M - Files Open-Ended Loops Here is a simple example of a script M-file that uses while to numerically stopping only when the condition not satisfied n = 1; while Condition_Expression(n==1) Statemets Do something here so that n not equal to 1 end

4.4 Breaking from a Loop


Sometimes you may want MATLAB to jump out of a for loop prematurely, for example if a certain condition is met. Or, in a while loop, there may be an auxiliary condition that you want to check in addition to the main condition in the while statement. Inside either type of loop, you can use the command break to tell MATLAB to stop running the loop and skip to the next line after the end of the loop. The command break is generally used in conjunction with an if statement. for n = 1:10 Statemets Statemets if Condition_break break end end Note: isnumeric is a function to test the type of the variable numeric.

4.5 Structure of Function M-files


MATLAB functions: Are useful for extending the MATLAB language for your application. Can accept input arguments and return output arguments. Store variables in a workspace internal to the function. This simple function shows the basic parts of an M-file. Note that any line that begins with % is not executable: function f = fact(n) Function definition line % Compute a factorial value. H1 line % FACT(N) returns the factorial of N, Help text % usually denoted by N! % Put simply, FACT(N) is PROD(1:N). Comment f = prod(1:n); Function body

20

Courseware on MATLAB Workshop

Chapter 4: Programming in MATLAB The M - Files The table below briefly describes each of these M-file parts. Both functions and scripts can have all of these parts, except for the function definition line which applies to functions only.

Figure Function details Function Definition Line The function definition line informs MATLAB that the M-file contains a function, and specifies the argument calling sequence of the function All MATLAB functions have a function definition line that follows this pattern. Function Arguments. If the function has multiple output values, enclose the output argument list in square brackets. Input arguments, if present, are enclosed in parentheses following the function name. Use commas to separate multiple input or output arguments. Here is the declaration for a function named sphere that has three inputs and three outputs: function [x, y, z] = sphere(theta, phi, rho) If there is no output, leave the output blank function printresults(x) or use empty square brackets: function [] = printresults(x) The variables that you pass to the function do not need to have the same name as those in the function definition line

21

Courseware on MATLAB Workshop

Chapter 5
MATLAB GRAPHICS
5.1 Basic 2-D graphs 5.2 Multiple Plots on the Same Axes 5.3 Multiple plots in a figure: subplot 5.4 3-D plots

The objective of this chapter is to introduce you to MATLABs high-level 2-D and 3D plotting facilities. A picture, it is said, is worth a thousand words. MATLAB has a powerful graphics system for presenting and visualizing data, which is reasonably easy to use.

5.1 Basic 2-D graphs


Graphs (in 2-D) are drawn with the plot function. In its simplest form, it takes a single vector argument as in plot(y). In this case the elements of y are plotted against their indexes, e.g. plot(rand(1, 40)) plots 40 random numbers against the integers 140, joining successive points with straight lines, as in Figure. If y is a matrix, its columns are plotted against element indexes. Axes are automatically scaled and drawn to include the minimum and maximum data points. Probably the most common form of plot is plot(x, y) where x and y are vectors of the same length, e.g. x = 0:pi/40:4*pi; plot(x, sin(x)) MATLAB has a set of easy-to-use plotting commands, all starting with the string ez. The easy-to-use form of plot is ezplot, e.g. ezplot(tan(x))

Chapter 5: MATLAB Graphics

Figure shows tan plot In the same way one can plot different standard functions Labels Graphs may be labeled with the following statements: gtext(text) writes a string (text) in the graph window. gtext puts a cross-hair in the graph window and waits for a mouse button or keyboard key to be pressed. The cross-hair can be positioned with the mouse or the arrow keys. Note: Text may also be placed on a graph interactively with Tools -> Edit Plot from the figure window. grid adds/removes grid lines to/from the current graph. The grid state may be toggled. text(x, y, text) writes text in the graphics window at the point specified by x and y. If x and y are vectors, the text is written at each point. If the text is an indexed list, successive points are labeled with corresponding rows of the text. title(text)

23

Courseware on MATLAB Workshop

Chapter 5: MATLAB Graphics writes the text as a title on top of the graph. xlabel(horizontal) labels the x-axis. ylabel(vertical) labels the y-axis.

5.2 Multiple Plots on the Same Axes


There are at least three ways of drawing multiple plots on the same set of axes (which may however be rescaled if the new data falls outside the range of the previous data). 1. The easiest way is simply to use hold to keep the current plot on the axes. All subsequent plots are added to the axes until hold is released, either with hold off , or just hold, which toggles the hold state. 2. The second way is to use plot with multiple arguments, e.g. plot(x1, y1, x2, y2, x3, y3, ... ) plots the (vector) pairs (x1, y1), (x2, y2), etc. The advantage of this method is that the vector pairs may have different lengths. MATLAB automatically selects a different color for each pair. If you are plotting two graphs on the same axes you may find plotyy usefulit allows you to have independent y-axis labels on the left and the right, e.g. plotyy(x,sin(x), x, 10*cos(x)) for x suitably defined. 3. The third way is to use the form plot(x, y) where x and y may both be matrices, or where one may be a vector and one a matrix. If one of x or y is a matrix and the other is a vector, the rows or columns of the matrix are plotted against the vector, using a different color for each. Rows or columns of the matrix are selected depending on which have the same number of elements as the vector. If the matrix is square, columns are used. If x and y are both matrices of the same size, the columns of x are plotted against the columns of y. If x is not specified, as in plot(y), where y is a matrix, the columns of y are plotted against the row index. Note: One can try other features by taking help on the plot, the markers and colors are also can be modified if required.

24

Courseware on MATLAB Workshop

Chapter 5: MATLAB Graphics

5.3 Multiple plots in a figure: subplot


You can show a number of plots in the same figure window with the subplot function. It looks a little curious at first, but its quite easy to get the hang of it. The statement subplot(m, n, p) divides the figure window into m X n small sets of axes, and selects the pth set for the current plot (numbered by row from the left of the top row). For example, the following statements produce the four plots shown in Figure subplot(2,2,1) ezplot(tan(x)),title(subplot(2,2,1)) subplot(2,2,2) ezplot(sin(x)) title(subplot(2,2,2)) subplot(2,2,3) ezplot(cos(x)) title(subplot(2,2,3)) subplot(2,2,4) ezplot(cot(x)) title(subplot(2,2,4)) Note: The command subplot(1,1,1) goes back to a single set of axes in the figure. Stem It is one of the function to get sample like plot of the functions or variables.

5.4 3-D plots


MATLAB has a variety of functions for displaying and visualizing data in 3-D, either as lines in 3-D, or as various types of surfaces.

plot3 The function plot3 is the 3-D version of plot. The command plot3(x, y, z) draws a 2-D projection of a line in 3-D through the points whose coordinates are the elements of the vectors x, y and z. For example, the command

25

Courseware on MATLAB Workshop

Chapter 5: MATLAB Graphics plot3(rand(1,10), rand(1,10), rand(1,10)) generates 10 random points in 3-D space, and joins them with lines, as shown in Figure

Figure shows the plot Mesh surfaces This drawing is an example of a mesh surface. To see how such surface is drawn, lets take a simpler example, say z =x2 y2. The surface we are after is the one generated by the values of z as we move around the x-y plane. Lets restrict ourselves to part of the first quadrant of this plane, given by 0 x 5, 0 y 5. The first step is to set up the grid in the x-y plane over which the surface is to be plotted. You can use the MATLAB function meshgrid to do it, as follows: [x y] = meshgrid(0:5); This statement sets up two matrices, x and y. (Functions, such as meshgrid, which return more than one output argument, The two matrices in this example are: x= 012345 012345 012345

26

Courseware on MATLAB Workshop

Chapter 5: MATLAB Graphics 012345 012345 012345 y= 000000 111111 222222 333333 444444 555555 The effect of this is that the columns of the matrix x as it is displayed hold the x coordinates of the points in the grid, while the rows of the display of y hold the y coordinates. Recalling the way MATLAB array operations are defined, element by element, this means that the statement z = x.2 - y.2 will correctly generate the surface points: z= 0 1 4 9 16 25 -1 0 3 8 15 24 -4 -3 0 5 12 21 -9 -8 -5 0 7 16 -16 -15 -12 -7 0 9 -25 -24 -21 -16 -9 0 For example, at the grid point (5, 2), z has the value 52 22 =21. Incidentally, you dont need to worry about the exact relationship between grid coordinates and matrix subscripts; this is taken care of by meshgrid. The statement mesh(z) then plots the surface, with mesh lines connecting the points in the surface that lie above grid points. Note that mesh(z) shows the row and column indices (subscripts) of the matrix z on the x and y axes. If you want to see proper values on the x and y axes use mesh(x,y,z). The function mesh draws a surface as a wire frame.

27

Courseware on MATLAB Workshop

Chapter 5: MATLAB Graphics

Note: There are many other graphics functions are available in the MATLAB one can refer documentation of MATLAB for the other functions and their features.

28

Courseware on MATLAB Workshop

Chapter 6
BEYOND BASICS OF MATLAB
6.1 String 6.2 Audio Processing 6.3 Image Processing

6.1 Strings
Enclosing text in single quotes forms strings with the char data type:
S = 'I love MATLAB'

To include a single quote inside a string, use two of them together, as in:
S = 'Green''s function'

Strings, numeric matrices, and other data types can be displayed with the function disp. Try disp(S) and disp(B).

Input Strings may be entered in response to the input statement in two ways: 1. You can enclose the string in apostrophes when you enter it, or 2. you can use an additional argument s with input, in which case you must not use apostrophes when entering the string, e.g. >> name = input( Enter your surname: , s ); Enter your surname: OReilly Strings are arrays A MATLAB string is actually an array with each element representing one character in the string. For example, if s = Napoleon whos reveals that s is 1-by-8. The statement who/whos will clear this fact. s(8:-1:1) will therefore display the string Napoleon backwards. String functions blanks generates a string of blanks. deblank removes trailing blanks from a string. int2str, num2str

Chapter 6: Beyond Basics of MATLAB convert their numeric arguments to strings. These functions are handy for labeling graphs with text which includes variable numeric values. ischar returns 1 if its argument is a string, and 0 otherwise. lower, upper convert strings to lowercase and uppercase, respectively. See help for a complete list of string-handling functions.

6.2 Audio Processing


MATLAB will provide a power-full speech and audio processing features. In this section we will discuss some of the audio feature available in the MATLAB. wavread Read Microsoft WAVE (.wav) sound file wavread supports multichannel data, with up to 32 bits per sample, and supports reading 24- and 32-bit .wav files. Syntax y = wavread('filename') Description y = wavread('filename') loads a WAVE file specified by the string filename, returning the sampled data in y. The .wav extension is appended if no extension is given. Amplitude values are in the range [-1,+1]. [y,Fs,bits] = wavread('filename') returns the sample rate (Fs) in Hertz and the number of bits per sample (bits) used to encode the data in the file. [...] = wavread('filename',N) returns only the first N samples from each channel in the file. [...] = wavread('filename',[N1 N2]) returns only samples N1 through N2 from each channel in the file. wavwrite Write Microsoft WAVE (.wav) sound file wavwrite writes data to 8-, 16-, 24-, and 32-bit .wav files. Syntax

30

Courseware on MATLAB Workshop

Chapter 6: Beyond Basics of MATLAB wavwrite(y,'filename') wavwrite(y,Fs,'filename') wavwrite(y,Fs,N,'filename') Description wavwrite(y,'filename') writes the data stored in the variable y to a WAVE file called filename. The data has a sample rate of 8000 Hz and is assumed to be 16-bit. Each column of the data represents a separate channel. Therefore, stereo data should be specified as a matrix with two columns. Amplitude values outside the range [-1,+1] are clipped prior to writing. wavwrite(y,Fs,'filename') writes the data stored in the variable y to a WAVE file called filename. The data has a sample rate of Fs Hz and is assumed to be 16-bit. Amplitude values outside the range [-1,+1] are clipped prior to writing. wavwrite(y,Fs,N,'filename') writes the data stored in the variable y to a WAVE file called filename. The data has a sample rate of Fs Hz and is N-bit, where N is 8, 16, 24, or 32. For N < 32, amplitude values outside the range [-1,+1] are clipped. wavplay Play recorded sound on PC-based audio output device Syntax wavplay(y,Fs) wavplay(...,'mode') Description wavplay(y,Fs) plays the audio signal stored in the vector y on a PC-based audio output device. You specify the audio signal sampling rate with the integer Fs in samples per second. The default value for Fs is 11025 Hz (samples per second). wavplay supports only 1- or 2-channel (mono or stereo) audio signals. wavplay(...,'mode') specifies how wavplay interacts with the command line, according to the string 'mode'. The string 'mode' can be 'async' (default value): You have immediate access to the command line as soon as the sound begins to play on the audio output device (a nonblocking device call). 'sync': You don't have access to the command line until the sound has finished playing (a blocking device call). The audio signal y can be one of four data types. The number of bits used to quantize and play back each sample depends on the data type. wavrecord Record sound using PC-based audio input device.

31

Courseware on MATLAB Workshop

Chapter 6: Beyond Basics of MATLAB Syntax y = wavrecord(n,Fs) y = wavrecord(...,ch) y = wavrecord(...,'dtype') Description y = wavrecord(n,Fs) records n samples of an audio signal, sampled at a rate of Fs Hz (samples per second). The default value for Fs is 11025 Hz. y = wavrecord(...,ch) uses ch number of input channels from the audio device. ch can be either 1 or 2, for mono or stereo, respectively. The default value for ch is 1. y = wavrecord(...,'dtype') uses the data type specified by the string 'dtype' to record the sound. The string 'dtype' can be one of the following: 'double' (default value), 16 bits/sample 'single', 16 bits/sample 'int16', 16 bits/sample 'uint8', 8 bits/sample Remarks Standard sampling rates for PC-based audio hardware are 8000, 11025, 2250, and 44100 samples per second. Stereo signals are returned as two-column matrices. The first column of a stereo audio matrix corresponds to the left input channel, while the second column corresponds to the right input channel. Examples Record 5 seconds of 16-bit audio sampled at 11025 Hz. Play back the recorded sound using wavplay. Speak into your audio device (or produce your audio signal) while the wavrecord command runs. Fs = 11025; y = wavrecord(5*Fs,Fs,'int16'); wavplay(y,Fs);

6.3 Image Processing


The Image Processing Toolbox is a collection of functions that extend the capability of the MATLAB numeric computing environment. The toolbox supports a wide range of image processing operations.

This section introduces some basic image processing concepts, including reading and writing images, performing some basic processing activity on an image 1. Read and Display an Image Clear the MATLAB workspace of any variables and close open figure windows. clear, close all To read an image, use the imread command. The example reads one of the sample images included with the Image Processing Toolbox, pout.tif, and stores it in an array named I.

32

Courseware on MATLAB Workshop

Chapter 6: Beyond Basics of MATLAB I = imread('pout.tif'); imread infers from the file that the graphics file format is Tagged Image File Format (TIFF). For the list of supported graphics file formats, see the imread function reference documentation. Now display the image. The toolbox includes image display functions: imshow. imshow is the toolbox's fundamental image display function. This example uses imshow. imshow(I) Note: The Image Appears in the Workspace as a matrix. To see how the imread function stores the image data in the workspace, check the Workspace browser in the MATLAB desktop. The Workspace browser displays information about all the variables you create during a MATLAB session. The imread function returned the image data in the variable I, which is a 291-by-240 element array of uint8 data. MATLAB can store images as uint8, uint16, or double arrays. You can also get information about variables in the workspace by calling the whos command. Improve Image Contrast pout.tif is a somewhat low contrast image. To see the distribution of intensities in pout.tif, you can create a histogram by calling the imhist function. (Precede the call to imhist with the figure command so that the histogram does not overwrite the display of the image I in the current figure window.) figure, imhist(I) Notice how the intensity range is rather narrow. It does not cover the potential range of [0, 255], and is missing the high and low values that would result in good contrast. The toolbox provides several ways to improve the contrast in an image. One way is to call the histeq function to spread the intensity values over the full range of the image, a process called histogram equalization. I2 = histeq(I); Display the new equalized image, I2, in a new figure window. figure, imshow(I2) Equalized Version of pout.tif Call imhist again to create a histogram of the equalized image I2. If you compare the two histograms, the histogram of I2 is more spread out than the histogram of I1. figure, imhist(I2) Write the Image to a Disk File

33

Courseware on MATLAB Workshop

Chapter 6: Beyond Basics of MATLAB To write the newly adjusted image I2 to a disk file, use the imwrite function. If you include the filename extension '.png', the imwrite function writes the image to a file in Portable Network Graphics (PNG) format, but you can specify other formats. imwrite (I2, 'pout2.png'); See the imwrite function reference page for a list of file formats it supports. Other Basic Image Processing functions im2bw rgb2gray uint16 uint8 imnoise Convert image to binary image by thresholding Convert RGB image or colormap to grayscaler Convert data to unsigned 16-bit integers (MATLAB function) Convert data to unsigned 8-bit integers (MATLAB function) Add noise to an image

34

Courseware on MATLAB Workshop

You might also like