You are on page 1of 96

Introduction to Computing with MATLAB

1 0.8 0.6 0.4 0.2 0 1 0.5 0 -0.5 -1 -1 0 -0.5 0.5 1

0.5

-0.5

-1 1 0.5 0 -0.5 -1 -1 -0.5 0.5 0 1

Preparatory Module
Addis Ababa University

Quantitative and Computational Skills Preparatory Module for Graduate Program Introduction to Computing with MATLAB

Prepared by Tadesse Abdi (PhD) Edited by Achenef Tesfahun (PhD)

Department of Mathematics Faculty of Science Addis Ababa University Aug. 2010

Table of contents Page


Introduction............................................................................................................2 First Step in MATLAB..........................................................................................3 Getting Started .................................................................................................3 The MATLAB Environment............................................................................4 Accessing a File at a Desired Directory.........................................................10 Working with MATLAB .....................................................................................13 Number Display Formats..............................................................................13 Variables, Constants and Assignments .........................................................15 Basic Operations and Navigation..................................................................17 Complex Arithmetic......................................................................................19 Saving and Retrieving Data .........................................................................21 Command, Algorithm and Program..............................................................21 On-line Help..................................................................................................22 Data Types in MATLAB .....................................................................................26 Fundamental Data Types .............................................................................26 Strings ..........................................................................................................28 Conversion to Strings...................................................................................29 Operations on Matrices .......................................................................................32 Selecting Part(s) of a Matrix ........................................................................32 Modifying a Matrix......................................................................................34 Special Matrices...........................................................................................36 Matrix Combination.....................................................................................37 System of Linear Equations .........................................................................45 Gaus Elimination ......................................................................................47 Relational and Logical Operations.....................................................................49 Relational Operations...................................................................................49 Logical Operations.......................................................................................51 Operator Precedence ....................................................................................53 Programming in MATLAB.................................................................................57 Control Flow ................................................................................................58 M-files..........................................................................................................65 Interrupting MATLAB.................................................................................69 MATLAB Graphics .............................................................................................70 Two Dimensional Plotting ...........................................................................70 Plot v/s fplot.................................................................................................75 Specialized 2D Plot Functions .....................................................................77 Three Dimensional Plotting .........................................................................84 Surface Plotting............................................................................................86 Importing MATLAB Graphics into Office Applications ............................89 Interpolation and Curve Fitting with MATLAB ..............................................91 Representing Polynomials ..........................................................................91 Curve Fitting ................................................................................................93 References.............................................................................................................94

Introduction
MATLAB is a high-level computing and visualization environment for science, engineering and technical problems. As a programming language and visualization tool, it provides a rich set of capabilities to deal with problems in engineering and science. As such, it integrates programming, computation and visualization in an easy-to-use environment. Data analysis, processing and computing in MATLAB is efficiently handled by matrix computation directly, as opposed to conventional computational environments whereby array dimensioning is required. Indeed, MATLAB has several advantages compared to other computational environments like C, FORTRAN, in terms of solving engineering and/or scientific problems. MATLAB is interactive software whose basic data element is an array. An array does not require dimensioning. The MATLAB environment consists of families of application-specific packages that integrate with MATLAB system, various specialized m-files designed to deal with particular/specific problems. Such an application-specific package is called a toolbox. In MATLAB there are toolboxes for control theory, optimization, partial differential equations, signal processing, symbolic computation, simulation etc. Above all, MATLAB has a user friendly graphics environment with commands that makes visualization of data immediately available. The acronym MATLAB stands for MATrix LABoratory. It was developed to be a numerical computing package intended originally to render an easy access to matrix software based on linear system package (LINPACK) and the eigen system package (EISPACK) routines. MATLAB is a case sensitive programming language that has sophisticated data structures, built-in editing and debugging tools. It supports object-oriented programming environment. Thus, MATLAB is a suitable language for scientific computing and hence an excellent tool for teaching and research. MATLAB is a commercial software package, available since 1984.

1. First Step in MATLAB


MATLAB is a software package for numerical computing that allows analysis of data, development of algorithms, building of models that mimic real world phenomena and supports visualization of desired results.

1.1 Getting Started


You can start MATLAB on MS windows platform in two ways. If your computer has started already, then either you put the cursor on the MATLAB Logo, i.e. the icon

which is available on your desktop and then double click or go to the start menu, put your cursor on all programs then follow the links as shown bellow

to get the icon , finally double click it. In either case, within a few seconds MATLAB will be evoked and you will see a screen like the following, the MATLAB desktop.

This is the MATLAB desktop/screen, composed of three parts (as you see), The Command window, Workspace window and the Command history window. To close MATLAB go to File menu and then choose Exit MATLAB or type one of the commands ``quit'' or exit at the MATLAB prompt and then hit return, i.e.
>> quit or >> exit

Or press the combination of keys ctrl-Q.

1.2 The MATLAB Environment


Basically, the MATLAB desktop environment has the following window components Command Window Command History Window Current Directory Window MATLAB Path Window Launch Pad Window Workspace Window and additional windows, such as o Editor Window o Figure Window

Command Window, also called MATLAB prompt window, is the primary place where you interact with MATLAB. As such, it is the main window where you type commands directly to the MATLAB for execution. The symbol >>, called MATLAB prompt is displayed in this window and afterwards a cursor | appears. A blinking cursor signifies that MATLAB is ready to accept and execute a command.

Command History Window is a window that displays all commands issued in MATLAB since the recent past session, i.e. all previous commands executed in a MATLAB session. It is useful for verification of a computational sequence. One can navigate through command window from the keyboard, using up-arrow, down-arrow, left-arrow and right-arrow. Up-arrow is used to repeat previous commands.

Launch Pad Window renders access to all MATLAB toolboxes and permits swift selection of a file or specific toolbox among all toolboxes. It provides a brief description of an m-file.

Upon stretching a given toolbox we may get a Demo window, as shown bellow for demonstration of that specific toolbox.

Workspace Window is used to view variable definitions along with variable memory allocations and array type. While you develop and execute a program i.e. a code in MATLAB, the workspace stores the underlying variable names and definitions on your behalf temporarily. The entire variables of the most recent operation are all available until you execute the command, >> clear.

Current Directory is a location where your code is available / saved and where MATLAB begins any operation. It is a window that helps quick access to files on the MATLAB path. If you are curious to know in which directory you are, just type pwd in front of the MATLAB prompt >> and then hit return. You will see a window as next.

MATLAB Path Window: displays all folders contained in the MATLAB, allow you to add/include folders to the MATLAB path or delete folders from the MATLAB path. A MATLAB program is oftentimes a plain text, i.e. an m-file saved with a given file name followed by a .m extension. Such an m-file is placed in one of the available directories. The list of all available directories can be displayed by using the command path >> path MATLABPATH C:\Program Files\MATLAB71\toolbox\matlab\general C:\Program Files\MATLAB71\toolbox\matlab\ops C:\Program Files\MATLAB71\toolbox\matlab\lang C:\Program Files\MATLAB71\toolbox\matlab\elmat C:\Program Files\MATLAB71\toolbox\matlab\elfun C:\Program Files\MATLAB71\toolbox\matlab\specfun C:\Program Files\MATLAB71\toolbox\matlab\matfun C:\Program Files\MATLAB71\toolbox\matlab\datafun C:\Program Files\MATLAB71\toolbox\matlab\polyfun C:\Program Files\MATLAB71\toolbox\matlab\funfun C:\Program Files\MATLAB71\toolbox\matlab\sparfun C:\Program Files\MATLAB71\toolbox\matlab\scribe C:\Program Files\MATLAB71\toolbox\matlab\graph2d C:\Program Files\MATLAB71\toolbox\matlab\graph3d C:\Program Files\MATLAB71\toolbox\matlab\specgraph C:\Program Files\MATLAB71\toolbox\matlab\graphics C:\Program Files\MATLAB71\toolbox\matlab\uitools C:\Program Files\MATLAB71\toolbox\matlab\strfun C:\Program Files\MATLAB71\toolbox\matlab\imagesci

C:\Program Files\MATLAB71\toolbox\matlab\iofun C:\Program Files\MATLAB71\toolbox\matlab\audiovideo C:\Program Files\MATLAB71\toolbox\matlab\timefun C:\Program Files\MATLAB71\toolbox\matlab\datatypes C:\Program Files\MATLAB71\toolbox\matlab\verctrl C:\Program Files\MATLAB71\toolbox\matlab\codetools C:\Program Files\MATLAB71\toolbox\matlab\helptools C:\Program Files\MATLAB71\toolbox\matlab\winfun C:\Program Files\MATLAB71\toolbox\matlab\demos C:\Program Files\MATLAB71\toolbox\matlab\timeseries C:\Program Files\MATLAB71\toolbox\matlab\hds C:\Program Files\MATLAB71\toolbox\local C:\Program Files\MATLAB71\toolbox\shared\controllib C:\Program Files\MATLAB71\toolbox\daq\daq C:\Program Files\MATLAB71\toolbox\daq\daqguis C:\Program Files\MATLAB71\toolbox\daq\daqdemos C:\Program Files\MATLAB71\toolbox\images\images C:\Program Files\MATLAB71\toolbox\images\imuitools C:\Program Files\MATLAB71\toolbox\images\imdemos C:\Program Files\MATLAB71\toolbox\images\iptutils C:\Program Files\MATLAB71\toolbox\shared\imageslib C:\Program Files\MATLAB71\toolbox\images\medformats C:\Program Files\MATLAB71\toolbox\optim C:\Program Files\MATLAB71\toolbox\shared\optimlib C:\Program Files\MATLAB71\toolbox\stats C:\Program Files\MATLAB71\toolbox\symbolic C:\Program Files\MATLAB71\work The command pwd stands for Print Working Directory, when entered at the MATLAB prompt window renders your current location/position in MATLAB. Whenever you run an m-file, MATLAB first search for that file in the current directory and then execute the program (if available) or returns an error message like ??? Undefined function or variable 'euler1'. otherwise.

Accessing a File at a Desired Directory: The command cd (change current directory), switches the current working directly (current working folder) to a desired directory. For instance >> cd c:/ change the current directory to the directory c. Once you are there you can create a new folder using the command mkdir followed by folder name. Type mkdir myfolder at the prompt, press ENTER and then see what it does. Again type cd myfolder hit return and then observe where you are. Editor Window is a window where we write a code. It is an interactive window allowing debugging of a source code and editing. The MATLAB Editor is a simple text editor whereby we develop a code and save complete MATLAB programs.

Figure Window displays graphic output from an m-file, a MATLAB code. MATLAB directs graphics output to a window that is different from the Command Window, i.e. the figure window. If you type figure at the MATLAB prompt and then press enter, i.e. execute the command >>figure you will get a figure window.

10

The Figure Window allows interactive change to plots and alteration of figure properties from the menu bars. One can add/include arrows, lines and a legend directly from the icons on top of a figure, under the menu bar.

To save a figure, you may select either Save As or Export from the File menu. If you select Save As you will be prompted to save it with .fig extension. But since, the use of graphics in different applications require different formats, e.g. .eps (Encapsulated post script), .emf (Enhanced metafiles) etc, selecting Export from the File menu includes all possible options. 11

12

2. Working with MATLAB


As a software package for numbers, i. Integer ii. Real iii. Complex numerical computing, MATLAB recognizes three types of 1362 217897 1.234 10.76 3 4i, i = 1

The MATLAB system has representations of the non numbers as well Inf for + e.g. generated by 1/o NaN Not a Number, obtained from mathematically undefined operations e.g. o/o or - , factorial(171) etc

2.1 Number Display Formats


In MATLAB, a number can be displayed only in discrete form, i.e. within a limited range and with a finite precision. Thus, Integers can be displayed exactly, Reals are represented by floating- point Origin of the term Floating-Point There is no fixed number of digits before/after a decimal point, i.e. the decimal point can float. The number of digits displayed is not related to the accuracy. When MATLAB displays numbers it follows a Format [obeys a rule]. The default Format is four digits after the decimal point. To change/override this format of the display, all we need to do is, typing format **** where **** is the format, this invoke any of the formats of your choice, e.g. format short e for scientific notation with 5 decimal places, format long e for scientific notation with 15 significant decimal places and format bank for placing two significant digits to the right of the decimal point. Example >> format long e >> 1/3 ans = 3.333333333333333e-001 >> 1.57

13

ans = 1.570000000000000e+000
>> 4 ans = 4

>> format short e >> 1/3 ans = 3.3333e-001 >> 1.57 ans = 1.5700e+000
>> 4 ans = 4

Different formats one may use to display the results of computation are summarized in the next table MATLAB Command Description format short 4 digits after the decimal point format long format short e format long e format short g long g + Bank Rat 14 digits after the decimal 5 digits and an exponent Floating point format with 15 digits. Best of fixed or floating point format with 5 digits. Best of fixed or floating point format with 15 digits. The symbols +, - and blank are printed for positive, negative, and zero elements. Imaginary parts are ignored. Fixed formats for dollars and cents. Approximation by ratio of small integers. 14 Comments Default full precision in decimal format

2.2 Variables, Constants and Assignments


A variable is a storage object/container that can hold a value. One can change a value stored in a variable, i.e. a new value can be stored in a variable already holding a value by overwriting/replacing the previous value. A constant is a quantity that never changes. A variable is created by an assignment Example >> x = 5 x= 5 MATLAB allows you create variables on the fly. To create a variable just use it on the left hand side of an equal sign. The following examples show how to assign values to three variables, x, y and w. It also shows the MATLAB response to the assignment statements. >> y = pi/4 y= 0.7854 >> w = y + x^0.25 w= 2.2807 Variable name begins with a letter followed by either a number or underscores or any such combinations. MATLAB recognizes only the first 31 characters. Thus, a variable name should contain at most 31 characters including the letter with which it commences. To call back the value of a variable that is already defined, type its name at the prompt and then press return . >> w w= 2.2807 If you want to know all active/current variables you are working with, just type the command who after the MATLAB prompt and press return, you will get a list of currently active variables as under,

15

>> who your variables are: w x y

The value of a variable can be a scalar, any number or a vector/matrix, >> x = 91 x= 91 >> y = [2 1 3] y= 2 1 3

>> z = [2 1 3;0 1 2] z= 2 0 1 1 3 2

The command WHO lists all the variables in the current workspace, i.e. it displays only variable names. The other command WHOS renders more information regarding each variable which includes number of allocated bytes and class of variables. >.> whos Name w x y Size 1x1 1x1 1x1 Bytes Class 8 double array 8 double array 8 double array

Grand total is 3 elements using 24 bytes.

16

2.3 Basic Operations and Navigation


MATLAB works with basic operations of arithmetic [addition, subtraction, multiplication and division], for scalars directly [usual way] and in case of vectors in two ways. The following table summarizes the symbol MATLAB accepts for the operations

Symbol + * / ^

Operation addition subtraction multiplication division exponentiation

All of these five operations work for any two numbers/scalars, integer, real or complex scalars. One can also add a scalar to [subtract a scalar from] each component of a vector/matrix, multiply or divide all the components of a vector/matrix by a scalar. A) Scalar Operation In order to carry out addition, subtraction, multiplication and division of scalars, one can first enter the values at the MATLAB prompt as follows >> u = 5; >> v = 3; and then apply the operation directly >> w = u + v w= 8 >> x = u v x= 2 >> y = u * v y=

17

15 >> z = u/v z= 1.6667 B) Vector/Matrix Operation As in the case of scalar-scalar multiplication, to carry out addition, subtraction, multiplication and division of vectors/matrix by scalars, first enter the values at the MATLAB prompt as follows >> x = 3; >> A= [2 0 6;4 2 0] A= 2 4 0 2 6 0

The colon at the end of value is used to suppress screen output. >> y = x + A y= 5 7 3 5 9 3

For a 2 x 3 matrix A, the expression x + A adds 3 to each component of A as demonstrated above, and x*A multiplies every component of A by 3 >> z = x*A z= 6 12 0 6 18 0

While A/2 divides each component of A by 2 >> w=A/2

18

w= 1 2 0 1 3 0

C) Command Window Navigation If you want to recall the most recent command entered at the prompt, all you need to do and are used to move along a command is press key. The other keys line from left to right and right to left respectively, thereby allowing swift editing of a command line. The most common command line editing keys and their function is summarized in the next table. Key ctrl- ctrl- Home End Esc del Backspace Alternative ctrl-p ctrl-n ctrl-f ctrl-b ctrl-r ctrl-l ctrl-a ctrl-e ctrl-u ctrl-d ctrl-h Description recall previous line Recall next line move forward one character move back one character move right one word move left one word move to beginning of line move to end of line clear line delete character at cursor delete character before cursor

2.4 Complex Arithmetic


The MATLAB environment recognizes complex numbers and allows working with complex numbers as with real numbers. The imaginary unity, i.e. i = 1 can be evoked by entering i at the MATLAB prompt.

>> a = i a= 0 + 1.0000i We can enter the complex number b = 1 + 2i in any one of the following ways. >> b = 1+2i b= 1.0000 + 2.0000i
19

or >> b = 1+2*i b= 1.0000 + 2.0000i The operations of addition, subtraction, multiplication and division in complex are supported in MATLAB.
Example: >> a=1+2i; >> b=2+i;

>> c = a+b c= 3.0000 + 3.0000i >> d = a-b d= -1.0000 + 1.0000i >> e = a*b e= 0 + 5.0000i >> f = a/b f= 0.8000 + 0.6000i Apart from the above four basic operations, the use of complex exponent is also possible. The next example evaluates the exponential function f ( x) = e x at x = i . 2 >> x = exp(pi/2*i) x= 0.0000 + 1.0000i which can be justified using Eulers formula e ix = cos( x) + i sin( x) .

20

MATLAB has several built-functions to determine some of the properties of complex numbers, that are summarized in the following table. function abs angle conj imag real syntax abs(z) angle(z) conj(z) imag(z) real(z) Description returns the modulus of z returns the argument(phase angle) of z in radians returns the complex conjugate of z returns the imaginary part of z returns the real part of z

2.5 Saving and Retrieving Data


In addition to accepting values and remembering variables, MATLAB can save and load/retrieve data from folders/files on the computer it is installed. Entering all values at the MATLAB prompt is not recommended, basically for this makes developing a program and debugging a bit inconvenient. The usual way is using the MATLAB editor window. To open the editor window simply, type edit at the prompt and then press return >> edit
Saving Data Once you write a code on the editor window, to save it click the File menu from the menu bar, choose the menu item save as, you will be provided with a dialog box where you are prompted to assign a name for your file, give a name by writing name.m with mextension and then click save. Retrieving Data To open your file all you need to do is again click the File menu from the menu bar and then choose the menu item open, pressing this opens the dialog box with all the files saved thus far, you can then choose the file you want to open and then either double click the file or click it once and then press the open button at the bottom of the dialog box.

2.6 Command, Algorithm and Program


A command is an instruction to do a specific task while an algorithm is a sequence of instructions for the solution of a given problem in a finite number of steps. A program is an implementation of an algorithm suitable for execution by a computer.
Comment A program you wrote might be used by somebody else. In this case the person who happens to see your code for the first time needs to know what it is all about, he/she will get this idea from an explanatory note[comment] included in the code. Every line of this

21

comment should commence with a symbol %. MATLAB will not execute any line of a code that begins with %.

2.7 On-line help


MATLAB renders help facility from documentation on-line. To use this facility you
need to type help followed by the command name at the prompt and then press return.
Example
>> help plus + Plus. X + Y adds matrices X and Y. X and Y must have the same dimensions unless one is a scalar (a 1-by-1 matrix). A scalar can be added to anything. C = PLUS(A,B) is called for the syntax 'A + B' when A or B is an object. Overloaded methods help zpk/plus.m help tf/plus.m help ss/plus.m help frd/plus.m help demtseries/plus.m help fints/plus.m help idmodel/plus.m help cvdata/plus.m help sym/plus.m

In the event that you are not sure about the exact name of the command but you know only part of the name, you can still get help from MATLAB, just type lookfor followed by the words you think are part of the name, upon hitting return all commands containing that word will be displayed with corresponding explanation on the MATLAB workspace. Apart from getting description of a specific file by typing help followed by the file name, i.e. command name at the MATLAB prompt, >> help file_name the comprehensive help commands available in the MATLAB system are

helpdesk helpwin

The command helpdesk displays a hypertext help browser in a new window as shown.

22

While helpwin opens all m-file help default topics i.e. a MATLAB help graphic user interface in a new window as follows.

23

For a comprehensive introduction to MATLAB help, type help help at the prompt and then press return >> help help HELP Display help text in Command Window. HELP, by itself, lists all primary help topics. Each primary topic corresponds to a directory name on the MATLABPATH. HELP / lists a description of all operators and special characters. HELP FUN displays a description of and syntax for the function FUN. When FUN is in multiple directories on the MATLAB path, HELP displays information about the first FUN found on the path and lists PATHNAME/FUN for other (overloaded) FUNs. HELP PATHNAME/FUN displays help for the function FUN in the PATHNAME directory. Use this syntax to get help for overloaded functions. HELP DIR displays a brief description of each function in the MATLAB directory DIR. DIR can be a relative partial pathname (see HELP PARTIALPATH). When there is also a function called DIR, help for both the directory and the function are provided. HELP CLASSNAME.METHODNAME displays help for the method METHODNAME of the fully qualified class CLASSNAME. To determine CLASSNAME for METHODNAME, use CLASS(OBJ), where METHODNAME is of the same class as the object OBJ. HELP CLASSNAME displays help for the fully qualified class CLASSNAME. HELP SYNTAX displays help describing the syntax used in MATLAB commands and functions. T = HELP('TOPIC') returns the help text for TOPIC as a string, with each line separated by /n. TOPIC is any allowable argument for HELP. REMARKS: 1. Use MORE ON before running HELP to pause HELP output after a screenful of text displays. 2. In the help syntax, function names are capitalized to make them stand out. In practice, always type function names in lowercase. For functions that are shown with mixed case (for example, javaObject) type the mixed case as shown. 3. Use DOC FUN to display help about the function in the Help

24

browser, which might provide additional information, such as graphics and more examples. 4. Use DOC HELP for information about creating help for your own M-files. 5. Use HELPBROWSER to access online documentation in the Help browser. Use the Help browser Index or Search tabs to find more information about TOPIC or other terms. EXAMPLES: help close - displays help for the CLOSE function. help database/close - displays help for the CLOSE function in the Database Toolbox. help database - lists all functions in the Database Toolbox and displays help for the DATABASE function. help general - lists all functions in the directory MATLAB/GENERAL. t = help('close') - gets help for the function CLOSE and stores it as a string in t. See also doc, docsearch, helpbrowser, helpwin, lookfor, matlabpath, more, partialpath, which, whos, class. Reference page in Help browser doc help

25

3. Data Types in MATLAB


The MATLAB system originally developed as a high level interface to a set of numerical computing packages based on LINPACK and the EISPACK routines has the basic data type, a two dimensional matrix/array containing real or complex floating point numbers. The smallest size of such a matrix is 0x0 i.e. an empty matrix [] and can vary form 1x1 matrix (a scalar) to an n-dimensional array of any size. Character array which is another data type supported by MATLAB environment is used to store text data.

3.1 Fundamental data types


There are about 15 fundamental data types in MATLAB. Each of which is in the form of an array, a matrix. All of the fundamental data types are indicated with oval circle in the following diagram.

Numeric data types in the MATLAB system include signed and unsigned integers, and single & double-precision floating-point numbers. By default, MATLAB stores all numeric values as double-precision floating point. You can choose to store any number, or array of numbers as integers i.e. as single-precision. Integer and single-precision arrays offer more efficient memory storage than double-precision. There are a number of data structures which extend the matrix structure in some what different ways. A prototype of these is a sparse matrices and cell arrays. In MATLAB one can store and operate on a matrix of any finite size, however, the memory size and computational performance of the computer is a factor to dictate the maximal size. In applications, there are real world problems represented by a matrix of sufficiently large size but with a few nonzero components, sparse matrix. Such matrices arise, for instance, in the analysis of communication networks, in finite element modeling etc. One 26

advantage of working with sparse matrices/arrays is, less storage space and much shorter evaluation time as compared to the corresponding full matrix.
Example

In finite element modeling of air flow over a wing of an airplane, computational grids are set up in such a way that they are densely space wherever the gradient of the solution is high. MATLAB has a built-in function, airfoil that solves this model. Help facility returns the next result. >> help airfoil AIRFOIL Display sparse matrix from NASA airfoil. The MATLAB function, airfoil contains suitable number of points distributed around the wing and the flaps of the airplane. The next few line of commands render the finite element solution of the problem as shown in the figure, right away. >> load airfoil >> figure >> plot(x,y,'o') >> axis equal

27

3.2 Strings
A string is an array of characters like, math 621, hello world, 2009 etc, surrounded by quotes. The MATLAB system represents characters with their ASCII values. >> x='math 621' x= math 621 Conversion between a character and the corresponding ASCII value is possible, use the built-in functions double and char. >> num=double(x) num = 109 97 116 104 32 54 50 49 >> y=char(num) y= math 621 The MATLAB built-in function strfun, with the help facility provides a complete set of commands for working with strings. >> help strfun Character strings. General. char double cellstr blanks deblank eval - Create character array (string). - Convert string to numeric character codes. - Create cell array of strings from character array. - String of blanks. - Remove trailing blanks. - Execute string with MATLAB expression.

String tests. ischar - True for character array (string). iscellstr - True for cell array of strings. isletter - True for letters of the alphabet. isspace - True for white space characters.

28

String operations. strcat - Concatenate strings. strvcat - Vertically concatenate strings. strcmp - Compare strings. strncmp - Compare first N characters of strings. strcmpi - Compare strings ignoring case. strncmpi - Compare first N characters of strings ignoring case. findstr - Find one string within another. strjust - Justify character array. strmatch - Find possible matches for string. strrep - Replace string with another. strtok - Find token in string. upper - Convert string to uppercase. lower - Convert string to lowercase. String to number conversion. num2str - Convert number to string. int2str - Convert integer to string. mat2str - Convert matrix to eval'able string. str2double - Convert string to double precision value. str2num - Convert string matrix to numeric array. sprintf - Write formatted data to string. sscanf - Read string under format control. Base number conversion. hex2num - Convert IEEE hexadecimal to double precision number. hex2dec - Convert hexadecimal string to decimal integer. dec2hex - Convert decimal integer to hexadecimal string. bin2dec - Convert binary string to decimal integer. dec2bin - Convert decimal integer to binary string. base2dec - Convert base B string to decimal integer. dec2base - Convert decimal integer to base B string. See also STRINGS.

3.3 Conversion to Strings


MATLAB has built-in functions, num2str and int2str for general purpose conversion of numbers to strings. The function int2str converts integer to string while num2str converts any number to string. The latter allows format specification. Consider dividing the number by 4. Whereas, direct computation returns the answer with only 4 significant digits, as shown bellow

29

>> x = pi/4 x= 0.7854 Format specification returns the desired result as per specified parameters, >> y = num2str(pi/4,'%12.6e') y= 7.853982e-001 The control of formatting involves the character %, the desired width and precision fields. Thus to display six decimal places in a field of 12 characters with exponential notation, we have to type it as in the above command. The MATLAB help facility with built-in function sprintf displays a complete list along with the description of various formatting options. >> help sprintf SPRINTF Write formatted data to string. [S,ERRMSG] = SPRINTF(FORMAT,A,...) formats the data in the real part of matrix A (and in any additional matrix arguments), under control of the specified FORMAT string, and returns it in the MATLAB string variable S. ERRMSG is an optional output argument that returns an error message string if an error occurred or an empty matrix if an error did not occur. SPRINTF is the same as FPRINTF except that it returns the data in a MATLAB string variable rather than writing it to a file. FORMAT is a string containing C language conversion specifications. Conversion specifications involve the character %, optional flags, optional width and precision fields, optional subtype specifier, and conversion characters d, i, o, u, x, X, f, e, E, g, G, c, and s. See the Language Reference Guide or a C manual for complete details. The special formats \n,\r,\t,\b,\f can be used to produce linefeed, carriage return, tab, backspace, and formfeed characters respectively. Use \\ to produce a backslash character and %% to produce the percent character. SPRINTF behaves like ANSI C with certain exceptions and extensions. These include: 1. ANSI C requires an integer cast of a double argument to correctly

30

use an integer conversion specifier like d. A similiar conversion is required when using such a specifier with non-integral MATLAB values. Use FIX, FLOOR, CEIL or ROUND on a double argument to explicitly convert non-integral MATLAB values to integral values if you plan to use an integer conversion specifier like d. Otherwise, any non-integral MATLAB values will be outputted using the format where the integer conversion specifier letter has been replaced by e. 2. The following non-standard subtype specifiers are supported for conversion characters o, u, x, and X. t - The underlying C datatype is a float rather than an unsigned integer. b - The underlying C datatype is a double rather than an unsigned integer. For example, to print out in hex a double value use a format like '%bx'. 3. SPRINTF is "vectorized" for the case when A is nonscalar. The format string is recycled through the elements of A (columnwise) until all the elements are used up. It is then recycled in a similar manner through any additional matrix arguments. See the reference page in the online help for other exceptions, extensions, or platform-specific behavior.
Examples sprintf('%0.5g',(1+sqrt(5))/2) 1.618 sprintf('%0.5g',1/eps) 4.5036e+15 sprintf('%15.5f',1/eps) 4503599627370496.00000 sprintf('%d',round(pi)) 3 sprintf('%s','hello') hello sprintf('The array is %dx%d.',2,3) The array is 2x3. sprintf('\n') is the line termination character on all platforms.

See also FPRINTF, SSCANF, NUM2STR, INT2STR. Overloaded methods help sgmltag/sprintf.m If controlling the formatting further is required, other characters need to be introduced into the conversion specifier. Look at the additional characters between % and the conversion character in the above examples.

31

4. Operations on Matrices
Recall, a matrix is a rectangular array of numbers with a given number of rows and columns, an m x n matrix has m rows and n columns. One can enter, for instance a 2 x 3 matrix,
1 0 2 A= 3 4 0

by typing either on a command line, on the editor window or directly at the MATLAB prompt, if it is entered at the prompt then pressing enter will produce the next result >> A = [1 0 2;3 4 0] A= 1 3 0 4 2 0

Components of a matrix are enclosed rectangular brackets, we use semicolon ; to separate rows while space is used to separate entries/components. MATLAB stores the above 2 x 3 matrix in the variable A. If you want to call this matrix, just type A at the prompt and then press enter.

4.1 Selecting Part(s) of a Matrix


In MATLAB the component on the row i and column j of a matrix A, i.e. the Aij entry is denoted by A(i,j). One can select/extract the component Aij by typing A(i,j) at the prompt and then pressing return
Example

>> A(1,3) ans = 2 A row of a matrix can be selected by specifying the row and then using the column : symbol as A(i,:). Here i specifies the row while the : allows to select all components along the specified row.
Example

>> A(2,:) ans =

32

3 4 0 Here MATLAB returns the second row and stores it in a temporary variable ans. Alternatively, we can define our own variable, say A_2 and store the second row in this variable as shown bellow A_2=A(2,:) A_2 = 3 4 0 A column of a matrix can also be picked in similar fashion as that of a row except for the interchange of a roll between colon : and the number i. Thus, the jth column of a matrix is selected by entering A(:,j).
Example

>> A3=A(:,3) A3 = 2 0 The colon operator : might be interpreted as either all rows or all columns. The symbol : colon can also be used to extract sub-matrix of a matrix, e.g. >> B=A(:,1:2) B= 1 3 0 4

or may be used to convert a matrix into a vector, e.g. >> C=A(:) C= 1 3 0 4 2 0

33

4.2 Modifying a Matrix


We can change components of a matrix by mere assignment. Consider the matrix M >> M = [1 0 2;3 4 0;5 2 3] M= 1 3 5 0 4 2 2 0 3

If we want to change M32 , say to 9 then we enter M(3,2)=9; >> M(3,2)=9; Call M to check the change >> M M= 1 3 5 0 4 9 2 0 3

A row/column of a matrix can be deleted by empty-assignment. To delete the second row of M , we do the following >> M(2,:) = [] M= 1 5 0 9 2 3

The symbol [] represents an empty matrix. Next, if we want to delete the third column, we can do it as follows >> M(:,3)=[] M= 1 3 5 0 4 2

34

MATLAB has built-in functions with which we may identify/determine properties of a matrix,
Example

>> size(M) ans = 3 Or more precisely >> [m n] = size(M) m= 3 n= 3 Tells us the dimension of the matrix we are working with, while >> D=diag(M) D= 1 4 3 Gives the diagonal components of M and >> Mt = M' Mt = 1 0 2 3 4 0 5 2 3 3

renders the transpose of M. The rank of a matrix can also be determined by using the command rank

35

>> rank(M) ans = 3

4.3 Special Matrices


There are several special matrices in MATLAB, other than the empty matrix [], with specific purpose, e.g. eye(m,n), zeros(m,n) & ones(m,n) >> zeros(2,3) ans = 0 0 0 0 0 0

A matrix of zeros, basically used to allocated computer memory for storage >> ones(2,3) ans = 1 1 1 1 1 1

A matrix of ones, basically used for the same purpose the matrix of zeros. >> eye(3) ans = 1 0 0 0 1 0 0 0 1

an identity matrix of order 3. For a square matrix, the MATLAB function rank can be used to decide if it is singular or otherwise. From linear algebra, a square matrix is singular provided it is rank deficient, i.e. for an n x n matrix to be non-singular it should have a rank of n. Since a non-singular matrix has a non-zero determinant, the MATLAB built-in function det that is used to compute the determinant of a matrix is also helpful.

36

>> det(M) ans = -16 For a non-singular square matrix, the inverse can be computed using the command inv >> inv(M) ans = -0.7500 -0.2500 0.5000 0.5625 0.4375 -0.3750 0.8750 0.1250 -0.2500

4.4 Matrix Combination


The basic operations of arithmetic (+, , *, /), already recognized by MATLAB can be used to combine two or more matrices.
A) Addition

If A and B are two matrices then we can add them to get a matrix C provided that they have the same dimension, for instance if
2 1 3 A= 5 4 0

and

0 1 1 B= 2 3 1

then, once we enter the matrices A & B as explained thus far, we simply type C=A+B at the prompt and press return, as always. >> A A= 2 5 >> B B= 0 -1 1 37 1 4 3 0

2 >> C = A+B C= 2 7

3 -1

0 4 7 -1

If the two matrices have different dimension then MATLAB send an error message
Example

>> A = [2 1 3;5 4 0] A= 2 5 1 4 3 0

>> D = [0 -1 1; 2 3 -1; 1 0 1] D= 0 -1 1 2 3 -1 1 0 1 >> E = A+D ??? Error using ==> + Matrix dimensions must agree.

B) Subtraction

MATLAB can handle subtraction of any two matrices like addition provided that their dimensions agree.
Example 1 2 5 0 2 3 3 3 2 and B = 1 2 1 For A = 2 0 1 1 0 1

We have

38

>> C = A-B C= 1 2 1
C) Multiplication

0 1 0

2 1 2

If A and B are two matrices such that the number of columns of A is the same as the number of rows of B then we can multiply A with B in that order, by typing A* B
Example

For the above two matrices A and B >> D = A*B D= 7 6 0 5 12 10 1 4 5 >> E = A.*B E= 0 3 2 4 15 6 2 0 -1

Observe! The difference between the operation *, and .*, Now delete the second row of B to get a 2 x 3 matrix as follows >> B(2,:)=[] B= 0 1 2 3 0 -1

39

If you multiply A with the resulting row reduced matrix B, MATLAB sends an error message complaining that there is a dimension mismatch. >> A*B ??? Error using ==> * Inner matrix dimensions must agree. Consider now another matrix pair,
1 2 C= 3 3

5 0 2 3 and D = 2 1 2 1

Since the number of columns of C is 3 and the number of rows of D is 2, if we try multiplying the two, MATLAB will not compute the product >> C*D ??? Error using ==> * Inner matrix dimensions must agree. However, if we modify the operation of multiplication, MATLAB will execute the job >> F = C.*D F= 0 3 4 15 6 2

In this case the multiplication is carried out component-wise. The operator (.*) often called array multiplication or element-element multiplication applies to any two matrix pairs provided that the two matrices have the same dimension. Thus if A=(aij) and B=(bij) are two m x n matrices then C = A.*B=(cij) where cij = aijbij , in particular if n=1, i.e. A and B are m-dimensional vectors,
A = (a1, a 2, ... an ) and B = (b1, b 2,... bn ) then

A.* B = (a1b1 , a 2b 2 ,... anbn )

For a matrix A, if A2 is understood as A x A then MATLAB executes A*A only if A is a square matrix whereas it accepts A . * A for any rectangular matrix.

40

D) Division

In MATLAB there are two matrix division operations, left matrix division or right matrix division, i.e. A\B or A/B. The left matrix division A\B arises in connection with method of solution of the set of equations, AX=B for X, whenever the coefficient matrix A, and the vector B are known. It is required that the matrices A and B have the same number of rows or A is a scalar. In the event that A is a scalar MATLAB performs the division A\B component-wise i.e. A\B = A .\B. Special case If A is a square matrix, A\B can be taken as A-1B, provided that A is non-singular, in this case the MATLAB syntax is inv(A)*B. A warning message may be displayed at the workspace if A is badly scaled or nearly singular.
Example

For two matrices


1 2 8 A = 4 0 2 2 3 0 1 2 4 B = 2 0 1 1 3 2

and

The left matrix division yields >> A\B ans = 0.4694 0 -0.4082 0.0204 1.0000 0.9388 0.0612 0 0.3163 If we want to apply division on each element of a matrix then we perform the componentwise matrix division as follows >> A.\B Warning: Divide by zero. ans = 1.0000 1.0000 0.5000 0.5000 NaN -0.5000 0.5000 1.0000 Inf In the above example the two matrices A and B have the same number of rows, indeed they have the same dimension. If we modify the matrix B by deleting its second row as 41

shown below, we have a 2 x 3 matrix B, and then apply the left division we get an error message from MATLAB. >> B(2,:)=[] B= 1 1 2 3 4 2

>> A\B ??? Error using ==> \ Matrix dimensions must agree. >> A.\B ??? Error using ==> .\ Matrix dimensions must agree. The operation A/B perform matrix right division. MATLAB accepts and executes A/B if B and A have the same number of columns, otherwise an error message is expected. For more information on matrix division and component-wise division, the MATLAB help facility can be evoked to reveal the next >> help .\ Operators and special characters. Arithmetic operators. plus - Plus + uplus - Unary plus + minus - Minus uminus - Unary minus mtimes - Matrix multiply * times - Array multiply .* mpower - Matrix power ^ power - Array power .^ mldivide - Backslash or left matrix divide \ mrdivide - Slash or right matrix divide / ldivide - Left array divide .\ rdivide - Right array divide ./ kron - Kronecker tensor product kron Relational operators. eq - Equal ne - Not equal == ~=

42

lt gt le ge

- Less than - Greater than - Less than or equal - Greater than or equal

< > <= >=

Logical operators. and - Logical AND & or - Logical OR | not - Logical NOT ~ xor - Logical EXCLUSIVE OR any - True if any element of vector is nonzero all - True if all elements of vector are nonzero Special characters. colon - Colon : paren - Parentheses and subscripting ( ) paren - Brackets [] paren - Braces and subscripting {} punct - Function handle creation @ punct - Decimal point . punct - Structure field access . punct - Parent directory .. punct - Continuation ... punct - Separator , punct - Semicolon ; punct - Comment % punct - Invoke operating system command ! punct - Assignment = punct - Quote ' transpose - Transpose .' ctranspose - Complex conjugate transpose ' horzcat - Horizontal concatenation [,] vertcat - Vertical concatenation [;] subsasgn - Subscripted assignment ( ),{ },. subsref - Subscripted reference ( ),{ },. subsindex - Subscript index Bitwise operators. bitand - Bit-wise AND. bitcmp - Complement bits. bitor - Bit-wise OR. bitmax - Maximum floating point integer. bitxor - Bit-wise XOR. bitset - Set bit. bitget - Get bit. bitshift - Bit-wise shift.

43

Set operators. union - Set union. unique - Set unique. intersect - Set intersection. setdiff - Set difference. setxor - Set exclusive-or. ismember - True for set member. See also ARITH, RELOP, SLASH, FUNCTION_HANDLE. There are MATLAB built-in functions that convert floating-point numbers to integers. The round function converts/rounds a floating-point number to the nearest integer, the floor function converts to the nearest integer towards negative infinity, the ceil function converts to the nearest integer towards positive infinity and the fix function converts/rounds to the nearest integer towards zero.
function Round Fix Floor Ceil description rounds to nearest integer rounds to nearest integer towards zero rounds down (towards negative infinity) rounds up (towards positive infinity)

The above table summarizes the functions and what they do. All of these functions are defined to work element-wise on matrices and vectors. For the sake of demonstration, referring to the two A and B given in the preceding example, if D is the resulting matrix from left division, >> D=A\B D= 0.4694 0 -0.4082 0.0204 1.0000 0.9388 0.0612 0 0.3163 Then the round function applied to D yields >> R=round(D) R= 0 0 0 0 1 0 0 1 0

44

The floor function applied to D gives >> F=floor(D) F= 0 0 0 0 -1 1 0 0 0

The ceil function applied to D renders >> C=ceil(D) C= 1 1 1 0 1 0 0 1 1

And the fix applied to D provides >> X = fix(r) X= 0 0 0 0 1 0 0 0 0

4.5 Systems of Linear Equations


Consider the following system of linear equations in the unknowns x, y, and z a11x + a12y + a13z = c1 a21x + a22y + a23z = c2 a31x + a32y + a33z = c3 The first step for solving this system with MATLAB is expressing the system as matrix equation. To this end, we need to form the matrix of coefficients, the matrix/vector of unknowns and that of the right-hand side, then establish the corresponding matrix equation as follows

45

a11 a12 a13 x b1 a 21 a 22 a 23 y = b2 a31 a32 a33 z b3

The number of rows of the coefficient matrix is the same as the number of equations while the number of its columns is equal to the number of unknowns in the equation, yet to be determined. The next step towards solving this system using MATLAB is entering the matrix of coefficients, and the column vector of the right-hand side

A =

a11 a12 a13 a 21 a 22 a 23 a31 a32 a33

b1 and B = b2 b 3

in MATLAB and store it in the variables A and B respectively. At this step we are ready to use MATLAB, the left division operation A\B gives a column vector, the components of which are the required solution.
Example

Consider the set of equations


1 2 3 x 1 4 5 6 y = 0 7 8 0 z 2

>> A=[1 2 3;4 5 6;7 8 0] A= 1 4 7 >> B = [1 0 2]' 2 5 8 3 6 0

46

B= 1 0 2 >> X=A\B X= -2.0000 2.0000 -0.3333

Gauss Elimination

The above system of equations can also be solved by using Gauss elimination. The next few lines of MATLAB code demonstrate this method. function [] = gausel(ab);
% % % % % Gauss ellimination with out row interchange for n-system of equations in n-unknowns with out back substitution. The Input is an augumented matrix. We end up with upper triangular system and the column vector of solution.

Clc, clear, close all [n m]=size(ab); c =ab(:,1:n); M=m-1; if n~=M error('Augumented matrix is not n by n+1') % elseif det(c)==0 disp('Matrix is ill Conditioned') else % for r=2:n % column reduction for i=r:n k(i)=ab(i,r-1)/ab(r-1,r-1); % ab(i,r-1:m) = ab(i,r-1:m)-k(i)*ab(r-1,r-1:m); % end end a=ab(:,1:n);b=ab(:,m); x=a\b UB=ab End

47

Excution of this code gives the same column vector of solution as the one obtained earlier by the MATLAB left division operation together with the corresponding upper triangular matrix. >> gausel([1 2 3 1;4 5 6 0;7 8 0 2]) x= -2.0000 2.0000 -0.3333 UB = 1 2 3 1 0 -3 -6 -4 0 0 -9 3 The above code made use of left division operator at the end of elimination step of Gauss procedure. However, if back substitution is considered in the process then one can compute the components of the solution vector starting with its last entry, without evoking left division operator as demonstrated by the following code.
function [] = gausbaksb(ab); % Gauss ellimination with back substitution, with out row interchange. clc close all [n m]=size(ab); c =ab(:,1:n); if det(c)==0 disp('Matrix is ill Conditioned') return else % for r=2:n % column reduction for i=r:n k(i)=ab(i,r-1)/ab(r-1,r-1); % ab(i,r-1:m) = ab(i,r-1:m)-k(i)*ab(r-1,r-1:m); % end end a=ab(:,1:n);b=ab(:,m); x(n)=ab(n,m)/ab(n,n); for i=n-1:-1:1 x(i)=(ab(i,m)-ab(i,i:n)*x(i:n)')/ab(i,i); end x=x'

end

48

5. Relational and Logical Operations


In addition to algebraic operators associated to traditional mathematical operations, the MATLAB system recognizes relational and logical operators and hence supports evaluation of a statement i.e. a proposition. As an input to a logical expression, the MATLAB system, like in C, considers any nonzero value to be true and zero to be false. Logical operators will return 1 for true.

5.1 Relational Operators


The most common MATLAB relational operators are summarized in the next table
Operator < <= > >= == ~= Description Less than Less than or equal to Greater than Greater than or equal to Equal Not equal

The relational operators are used by MATLAB to compare i. two arrays of identical size ii. an array to a scalar In the case i. comparison is made component-wise and a logical value is assigned to every pair of corresponding entries whereas in the latter case, the scalar is compared to every entry of the array. In either case, the result has the same size as the array.
Example 1

>> A = [1 2 1;3 2 1] A= 1 3 >> B = [-1 1 0;4 3 5] B= -1 4 1 3 0 5 2 2 1 1

49

>> C=A>B C= 1 0 1 0 1 0

Example 2

>> D= [1 2 4;3 0 5] D= 1 3 >> E = [1] E= 1 >> F=D>E F= 0 1


Example 3

2 0

4 5

1 0

1 1

>> G = [2 4;3 0] G= 2 3 >> H = G = = G' H= 1 0 0 1 4 0

50

Remark: The symbols =, and = =, are used by MATLAB for two different purposes, =, is used to assign a logical value of the output of an operation to a variable, while = =, is employed to compare two variables and return a logical value, i.e. 1 if they are equal and 0 otherwise.

Relational operators can also be used to extract components of an array satisfying a certain condition, by logical addressing.
Example

>> x = [1 3 1 2 1] x= 1 >> y = (x==1) y= 1 0 1 0 1 3 1 2 1

The same members can be extracted by using the MATLAB built-in function find, which renders the indices (positions) of such elements. >> z = find(x==1) z= 1 3 5

5.2 Logical Operators


Logical operators are used to combine statements/expressions or to alter a statement. The logical operators recognized by MATLAB system includes,
Operator & | ~ Description And Or Not

The not operator ~, often called negation is a unitary operator that converts 0 entries of an array to 1 and all other entries to 0, i.e. swaps where the 1s and 0s appear.

51

Example 1

>> A = [2 4;3 0] A= 2 3 >> C = ~(A==A') C= 0 1


Example 2

4 0

1 0

>> A = [2 4;3 0 ] A= 2 3 >> C = (A<2)&(A>=0) C= 0 0 0 1 4 0

Other than the above listed relational and logical operators, the MATLAB system provides a number of additional logical and relational operators/functions, binary and unitary.
Function Xor Any All Description exclusive or any element of an array non zero? all element of an array non zero?

The syntax for exclusive or, xor is


xor (, )

It returns 0s when

52

i. and are zero ii. and are non zero and returns 1s when either or is non zero, but not both. It is required that and should have the same size/dimension or one of them is a scalar. The operator/function, any, returns 1 if any entry in a vector is non zero, at least one component. The corresponding syntax is any(). For a matrix M, any(M) returns 1 for each column that has a non zero component. Finally the function all, which is a unitary operator, returns 1 if every component of a vector is non zero. The syntax is all(). If M is a matrix then all(M) returns 1 for each column of M that has all non zero components. The operators any and all are functions to determine if a matrix has at least one nonzero entry or all the entries are nonzero, respectively.With both functions/operators, if either argument is a scalar, the operation is done with that scalar on each component. Otherwise, both vectors/matrices must have the same size and the operation is done component wise.

5.3 Operator Precedence


The logical operators & and | have equal precedence in MATLAB. Hence, within a pair of parentheses, expressions are evaluated from left to right. >> a = 1|5 a= 1 >> b = 0 b= 0 >> c = a&b c= 0 >> d = (1|5)&0 % this agrees with the above result

53

d= 0 >> e = 1|(5&0) e= 1 It is recommended that, you use parentheses to expressions of this type so as to avoid possible problems with the interpretation of your code by MATLAB. When you write a code, you know what's going on, but afterwards, say a week or so, you may forget the details. Thus, it is advisable to write the detail from the beginning so that when you go through the code any other time you read it fast. The following, while still complicated, can be parsed with much greater ease.
>> ((3:(6+2):17)<5)|(((5:(2*3):(22-5*2))>(19*4))&(~sin(4:5)>0.2))

% this gives wrong result

Not only is this convenient for you when you get back to look at your own code, but also if somebody else looks at your code, then he/she won't have to spend a lot trying to understand and determine what it is. Furthermore, if there was an error in your code, all somebody else other than you can do is, first understand what you did, then try to determine what you meant, and then fix it. There are still numerous functions which MATLAB system provides for testing the existence of specific conditions and that return logical values. A partial list of these functions is given in the next table.
Test function isfinite isempty isglobal ishold isieee Isinf isletter isnan isreal isspace issparse Isstr isstudent Description Return true where elements are finite Return true if argument is empty Return true if current a global variable Return true if current plot hold state is ON Return true if computer performs IEEE arithmetic Return true where elements are infinite Return true where elements are letters of the alphabet Return true where elements are NANs Return true if argument has no imaginary part Return true where elements are whitespace characters Return true if argument is a sparse matrix Return true if argument is a character string Return true if the MATLAB version is student edition

54

Example

>> A = [5 nan 8 inf] A= 5 NaN


Remark

8 Inf

In use, NaN can be in lower case, one can inter lower case letters.

>> B = 2*A B= 10 NaN 16 Inf

>> C = sqrt(A) C= 2.2361 NaN 2.8284 Inf

In these two computations, all the operations on NaNs result in NaNs. This is, indeed in conformity with the IEEE mathematical standards. However, the following two relational operations produce a kind of strange, rather unexpected output. >> D = (A= =nan) D= 0 >> E = (A ~ = nan) E= 1 1 1 1 0 0 0

On the one hand, the operation on NaN, D = (A= =nan) produces all 0s, false results even when Nan is compared with NaN, i.e. individual NaNs are not equal to each other. On the other hand, E = (A ~ = nan) produces all 1s, true results. Due to this factor, MATLAB has a built-in function (logical function), isnan, which can identify/find NaN.

55

>> D = isnan(A) D= 0 1 0 0

This built-in function, isnan can be used in conjunction with the other built-in function find to identify the index of the entry with NaN. >> i = find(isnan(A)) i= 2 This tells us that the second entry of the array is NAN. >> A = [4 NaN 9 inf 3] A= 4 NaN >> E = find(A==0) E= [] In the event that none of the components of an array matches the value with which it is compared, the built-in function find returns an empty matrix, as seen from the preceding example. 9 Inf 3

56

6. Programming in MATLAB
The MATLAB system which started as an interactive software package for doing matrix computations has now grown to a high level programming language extensively used both in research and teaching. The capabilities of MATLAB are extended through programs written in its own syntax. It provides the standard control flow statements, loops and conditionals. The control flow commands can be used interactively to reduce the tedium of repetitive tasks. As a programming language, MATLAB is case sensitive (e.g. a is different from A) and shares some of the terminologies used by conventional programming languages, e.g bit, byte etc. bit (binary digit) the smallest unit of information. One bit can hold only one of the two values 0 or 1.

byte kilobytes megabytes gigabytes data data type file ASCII file binary file

a unit of 8 bits. capable of holding a single character. 1024 bytes 1024 kilobytes 1024 megabytes information in symbols( e.g. numbers, words, signals, images etc) classification of a particular type of information (e.g. integer, floating point, character) collection of data, information with a name. a standard, readable and editable plain text. a file stored in a format readable only by computers, not human readable. MATLAB binary files have .mat extension, i.e. of the form *.mat an instruction to do a specific task. a finite sequence of instructions for the solution of a specific task. implementation of an algorithm. an error in a program the process of finding and fixing a bug. a storage that can hold a value. a value that never change.

command algorithm program bug debug variable constant

57

6.1 Control flow


A control flow structure in MATLAB is a block of commands that allows conditional execution of a code and making loops. In other words, Programming in MATLAB offers features that allow one to control the flow of command execution based on decision making structures. MATLAB offers about four decision making structures, to control the flow through your code. These are,

For loops While loops If-else-End constructions Switch case

structures. Since these structures usually encompass a number of MATLAB commands, they often appear in m-files.

A) The For loop

The For loop permits repeated execution of a group of commands a certain number of times, a block of commands will be repeated a fixed number of times. The syntax is; for i = : h : commands end

The commands between the for and end statements are executed once for each index i from to . At each iteration, i is assigned to the next index.
Example

>> x = 1:2:3; >> y = zeros(1,length(x)); >> for I = 1:length(x) y(i)= sin(pi/x(i)); end >> y y= 0.0 0.8660

With For loops nesting is always possible, i.e. can be nested as desired.

58

Example

>> for i=1:3 for j=1:3 A(i,j)=i+j; end end >> A A= 2 3 4 3 4 5 4 5 6

The MATLAB for loop is comparable to a Fortran do loop or a C for loop. A for loop repeats the commands/statements in the loop as the loop index takes on the values in a given row vector: >> for i=[2 3 4 5] disp(i^2) end 4 9 16 25
Note! The use of the built-in function disp, is simply to display its argument. This loop would more commonly be written as

>> for i=2:5 disp(i^2) end 4 9 16 25 Observe that 2:5 is the same as [2,3,4,5]. 59

Execution of a for loop generally takes longer time. Hence, whenever there is an equivalent array approach, a for loop should be avoided for solving a particular problem. For the sake of demonstration, consider the same problem above, >> tic >> for i=2:5 disp(i^2) end >> toc 4 9 16 25 elapsed_time = 0.0470 Execution of the same commands in an array format as show bellow, takes different run time. >> tic >> i=[2 3 4 5]'; >> disp(i.^2) >> toc 4 9 16 25 elapsed_time = 0.0310 The elapsed time, the time it took the computer to compute the command is significantly shorter in the latter case. Hence arrays are preferred for maximal speed.
Example

The MATLAB system supports construction of tabular values by using the for loop, as can be seen from the next example.
% mytable.m % Tabular display of values % Short table of sine function

60

clc, clear all,close all n=10; x=linspace(0,1,n); y=cos(2*pi*x); disp('--------------------') disp(' k x(k) sin(x(k))') disp('--------------------') for k=1:n degrees=(k-1)*360/(n-1); disp(sprintf(' %2.0f %3.0f %6.3f ',k,degrees,y(k))) end disp('---------------------') disp('x(k) is given in degrees.') disp(sprintf('One degree = %5.3e Radians',pi/180))

The above code, to see what it does, first store the file with the name mytable, i.e. save as mytable.m or any name of your choice, for that matter but with .m extension, then call the file at the command widow by typing its name at the prompt, finally press return. >> mytable
-------------------k x(k) sin(x(k)) -------------------1 0 1.000 2 40 0.766 3 80 0.174 4 120 -0.500 5 160 -0.940 6 200 -0.940 7 240 -0.500 8 280 0.174 9 320 0.766 10 360 1.000 --------------------x(k) is given in degrees. 1 degree = 1.745e-002 Radians

B) The While loop

The while loop resembles the for loop in that it allows repeated execution of MATLAB commands / statements. The while loop executes a command or group of commands indefinite number of times, until some condition is met. The corresponding syntax has the following form.

61

while expression commands end where expression is a logical expression that has a logical value, either true or false.The commands between the while and the end are executed as long as the expression is true, executed repeatedly while the value of the expression is 1. In other words, a while loop iterates a body of commands as long as a condition holds true.
Example

>> n = 1; sum=0; >> while n <= sum = sum + n^2; n=n+1; end >> sum

% initialize % update

The above script is a MATLAB program that uses while loop to compute the sum of the squares of natural numbers less than or equal to , i.e. the sum of a finite series 12 + 22 + 32 + ... + 2 A while loop with infinite number of iterations can also be constructed, by specifying the logical value of the expression to be true over all iteration.
Example

>> while 1 commands end is an infinite loop constructed by using the statement 1, which is always true. One can terminate this loop by using a break statement as follows >> while 1 commands break end One can construct a do-until loop as follows >> expr = 1; >> while expr commands expr = ; end

62

where again, is a logical statement. A do-until loop executes at least once, whereas a while loop may never execute the statement commands.
C) The If-else-End Structure

There are situations where you need a certain part/parts of a program/code to be executed only under some specific circumstances. The way to do that in MATLAB is to put the code within an "if" statement, i.e. introducing conditionals. The simplest if-else-end structure is; if expression commands end

The command/commands between the if and end statements are evaluated provided that the logical value of the expression is true. There are other variants of conditional execution, e.g. if-else-end where there are two alternatives and if-elseif-else-end for several alternatives. The corresponding syntax for if-else-end structure is; if expression commands else commands end

% executed if True % executed if False

In this case, the first set of commands is executed if expression has a logical value True, otherwise the second set of commands is executed. In the event that there are three or more alternatives/conditions, the if-else-end structure transforms to if expression(1) Commands % executed if expression(1) is True elseif expression(2) Commands % executed if expression(2) is True else Commands % executed if expressions 1 & 2 are False end Here, the last else may or may not appear.

63

Example
function [] = extrm4(a,b,c); clc, clear all x=-b/(2*a); y=(4*a*c-b^2)/(2*a); if a>0 disp(' ') x=x max=y elseif a<0 disp(' ') x=x min=y else disp(' ') disp('Quadratic fla is not applicable') end

This is a function m-file, a MATLAB code to compute the extreme value of a quadratic function. It accepts the coefficients as input and returns the maximum or the minimum value.
D) The Switch Construct

As opposed to a while loop that executes the same sequence of commands for each input, a switch construct performs different sequence of commands in different cases, depending on the input. The switch command permits branching among several cases. The syntax for the MATLAB command, switch is; switch (expression) case expr(1) commands case expr(2) commands otherwise commands end where expression is either a scalar (1x1 matrix) or a string. If expression matches expr(1) then the commands following the first case will be executed. If expression matches none of the cases then the commands following otherwise are executed. In other words, when expression matches a case, then only the commands between the matching case and the immediate next case are executed, and if none of the case match with the expression, the commands between otherwise and end are executed.

64

The following two are equivalent: A) switch expression case 1 commands case {2,3} commands 2 3.... otherwise commands end if x == 1 commands elseif any( x == [2, 3] ) commands 2 , 3 else commands end

B)

6.2 M-files
We can compute in MATLAB by entering the commands directly at the Command window, prompt window. Whereas this is an advantage for simple tasks, it is generally insufficient for complex problems. Instead, a much convenient approach that makes debugging also easier is the use of MATLAB editor window, a built-in debugger window. Here, you can type lines of commands, inputs and then store it in a file with .m extension. Such a file is called an M-file.

A) Script m-file

An m-file that contains MATLAB commands as you would enter them at the prompt window is called script m-file. To demonstrate construction of a script m-file we shall write a MATLAB code that plots the graph of the function f ( x) = 6 x6 10 x 4 + 3 x 2 + 1 on the interval I = [1.5 ,1.5] . It suffices to enter the following 5 lines of commands at the prompt window in that order to visualize the required graph >> x = linspace(-1.5,1.5); 65

>> y = 6.*x.^6-10.*x.^4+3.*x.^2+1; >> plot(x,y) >> grid on >> axis([-1.5 1.5 -0.1 3.5])

The script m-file, written to solve the above problem has the following format

The above script m-file is saved with the name that has an extension .m, mygraph.m

Upon typing only the name of the file (without the extension) mygraph in the MATLAB prompt, those commands are executed as if they had been entered at the prompt window, and returns the graph depicted bellow.

66

The m-file should be located in a directory which MATLAB automatically checks for mfiles. One of the directories in which MATLAB always looks is the current working directory; the command cd may be used to identify the current working directory, >> cd C:\MATLAB6p1\work Alternatively, the command pwd can also be used for the same. >> pwd ans = C:\MATLAB6p1\work

B) Function m-file

An m-file that accepts an input and returns an output [a result] is called a function m-file. It is much more powerful than a script m-file. A function m-file communicates with MATLAB workspace through the variables assigned to it and the output variables it

67

creates. A function m-file is defined in an m-file that begins with a line of the following form, function [output1, ... , output n] = name(input1 , ... , input m) The remaining lines of the m-file consist of sequences of the usual MATLAB commands for computing the values of the outputs and performing desired actions. Consider the following function m-file designed to compute the GCF and LCM of two integers,
function [G,L] = hcfscm(m,n) % This program is an implementation of % Euclid's Algorithm % so as to compute the highest common factor % and the smallest common multiple of two integers. % clc, close all if (nargin >= 3) error('Too many input arguments') elseif (nargin < 2) error('Not enough input arguments') return; elseif m==n g=m; L=m; disp('--------------') disp(' HCF SCM ') disp('--------------') disp(sprintf(' %2.0f %2.0f',g,L)) disp('--------------') else a=min(m,n); b=max(m,n); d=b-a; while d>0 b=max(a,d); a=min(a,d); d=b-a; if d<0 break end end g=d+a; L=(m*n)/g; % disp(' ') disp('--------------') disp(' HCF SCM ') disp('--------------') disp(sprintf(' %2.0f %6.0f',g,L)) disp('==============') disp(' ') disp('HCF = highest common factor disp('SCM = smallest common multiple disp(' ') end

') ')

68

As can be seen from this example, the first line of the m-file defines the file as a function, specifies its inputs/outputs and is used to designate the function name. The name of the file and the function name should be identical. The rest of the lines that commence with % is a sequence of comments which will be displayed when help facility is evoked at the prompt. The remainder of lines of the m-file are commands to create output variables when executed. At the risk of repeating ones self, we re-emphasize a potentially troublesome point. In order to execute an m-file, MATLAB must be able to find it. Which means that it should be available in a directory in MATLAB's path. The current working directory is always on the path to display or change the path, use the path command. To display or change the working directory, use the cd command. As usual, help will provide more information.

6.3 Interrupting MATLAB


After we enter a command at the MATLAB prompt, for whatever reason, if we want to stop MATLAB from executing the job, we can interrupt it by pressing the pair of keys ctrl-c

69

7. MATLAB Graphics
The MATLAB environment supports graphic display of a known function, data resulting from experimental measurements or from engineering and/or scientific computation through various built-in functions for plotting. It also provides control facility over graphic properties.

7.1 Two Dimensional Plotting


The most commonly used graphics display function in MATLAB is the function plot, and the syntax is plot(x,y), where x and y are two n-dimensional arrays.
Example

Consider two arrays X = [1 2 3 4 5 6] and Y = [1 4 9 16 25 36] The following lines of commands plots the array Y against array X >> X = [1 2 3 4 5 6]; >> Y = [1 4 9 16 25 36]; >> plot(X,Y)

70

In the above example, six data points are given to MATLAB and then the function plot connected these consecutive points with lines, i.e. interpolates the data points. These six data points, {(1,1),(2,4),(3,9),(4,16),(5,25),(6,36)}used in the above plot are among the points that lie along the graph of the function y = x2. If an analytic formula of a function is known then to visualize its graph we dont need to list the discrete points, it suffice to discretize the domain, MATLAB can then evaluate the function at each discrete point in the domain and render the data points for interpolation. We can discretize a domain either by using the colon : operator or using MATLAB built-in functions
Example

Consider the interval, I = [1, 6] of the real line. >> X=1:6 X= 1 2 3 4 5 6

The colon operator : as used above, generates the discrete representatives of the given interval with the difference between any two consecutive members 1, called the step size. This is the default use of the colon operator. In the general case, one specifies the step size r, a number larger or may be smaller than 1 depending on the number discrete points he need for his purpose. >> z = 1:0.5:6 z= Columns 1 through 7 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000 Columns 8 through 11 4.5000 5.0000 5.5000 6.0000 The above numbers are discrete representatives of the same interval I = [1,6], generated with step size 0.5. Among several MATLAB built-in functions, linspace that can do the same job >> x = linspace(1,6,11) x= Columns 1 through 7

71

1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000 Columns 8 through 11 4.5000 5.0000 5.5000 6.0000 In the argument of the MATLAB function linspace, 11 represents the number n of discrete points needed, while 1 and 6 are the left and right end points of the interval. The default value of n is 100. >> x=linspace(-4,5); >> y=x.^3-2*x.^2-x+2; >> plot(x,y) >> grid >> title('The Graph of y = x^3-2x^2-x+2')

The function grid forces MATLAB to turn on the current axes' grid lines while the function title outputs the preferred string at the top and in the center of the current axes. The Syntax is, title('string').

Multiple graphics

We can visualize the plot of two or more graphs on the same set of axes. These can be done either by plotting them both at the same time, the syntax is plot(x, f, x, g) or 72

through the use of the command hold on/off. In what follows, we try to visualize the graphs of f ( x) = x3 2 x 2 x + 2 and g ( x) = 2 x3 + 2 in one and the same set of axes, by plotting them at the same time. >> x=linspace(-4,5); >> f = x.^3 - 2.*x.^2 - x + 2; >> g= 2.*x.^3+2; >> plot(x,f,x,g,'.-') >> legend('y = x^3-2x^2-x+2','y=2x^3+2') >> grid

Next we shall use the command hold on/off to generate the same set of graphics with MATLAB as the preceding one. In this case, we call the function plot twice between the commands hold on and hold off as indicated bellow. >>x=linspace(-4,5); >>f = x.^3 - 2.*x.^2 - x + 2; >>g = 2.*x.^3+2; >>hold on >>plot(x,f) >>plot(x,g,'.-g') >>hold off >>legend('y = x^3-2x^2-x+2','y=2x^3+2') >>grid 73

One can use a single window to visualize several plots one after the other without overlay. The command clf ensures an empty figure window. In case a graphics window is hidden under other active windows on the desktop, the command shg helps bring graphics window to the front.
Plotting Options

When visualizing several plots on the same set of axes one has to do something to distinguish between different plots. MATLAB has a facility that enable us do this. Each plot can be given its own distinctive look by modifying, either the way the points are plotted i.e. as a solid line, as points, as point-line etc, or by using different colors green blue, red, etc for different curves. These graphic features are specified by introducing a 3rd argument in the function plot, The syntax is plot(x,y,s) where s is a character string composed of a letter for color and others for line type and plot symbol. Possible colors we may use are as depicted in the following table
character r g b c m y w k Color Red Green Blue Cyan magenta yellow White Black

74

The default color is blue. When plotting a line, we may change the appearance of a line by using one of the following characters
character : -. -line type Solid dotted dash dot dashed

The default line is solid. In plotting curves it is possible to use symbols rather than lines, we can do this by using any one of the following symbols
character o x + * s d v ^ < > p h Plot v/s fplot plot symbol Point Circle an x Plus Star square diamond triangle (down) triangle (up) triangle (left) triangle (right) pentagram hexagram

The quality of a graph visualized by the command plot on a given set (interval) varies with the number of discrete points used. The more the number of discrete points the smoother the graph will be. The built-in function plot which interpolates neighboring data points linearly, may not capture all possible feature of the graph of the function, especially when the function varies slowly on some portion of its domain and pretty fast on some other. The command fplot is capable of displaying features of the graph of a function f. The syntax is fplot(f, [Xmin Xmax]) We might want to visualize several plots side by side, without overlaying them. In MATLAB this is possible. To display multiple plots in the same window but with different axes, the built-in function subplot divides the current figure window into rectangular panes with each pane containing an axes object such that subsequent plots are displayed on the current pane. The syntax is subplot(m,n,p) or just subplot(mnp). The command subplot(mnp), partitions the figure window into an m-by-n matrix of small

75

axes and then selects the pth axes for the current plot. The axes are counted from left to right along rows of the figure window starting with the first.

The above figure window is subdivided into 2 x 2 matrix of separate axes and is generated with the script bellow >>x=linspace(-6,8); >>f = x.^3 - 2.*x.^2 - x + 2; >>g= -2.*x.^3+2; >>h=sin(x); >>k=cos(x); >>subplot(221) >>plot(x,f) >>legend('y = x^3-2x^2-x+2') >>grid >>subplot(222) >>plot(x,g,'g') >>legend('y=-2x^3+2') >>grid >>subplot(223) >>plot(x,h,'c') >>grid >>legend('y=sinx') >>axis([-6 8 -2 2]) >>subplot(224) >>plot(x,k,'m') >>axis([-6 8 -2 2]) 76

>>legend('y=cosx') >>grid

7.2 Specialized 2D Plot Functions


A) Implicit Plot Thus far, we have been displaying the graph of a function f which has explicit analytical formula/expression. The MATLAB built-in function plot, accepts the discritized domain (an array X), evaluates f at each x X (generates an array Y) and then returns graphics which is the plot of vector Y against vector X. If a function f of two variables is defined implicitly, such a procedure may not apply and hence the built-in function plot can not be used. In such a situation, the other MATLAB built-in function plotter ezplot serves the purpose. The syntax is ezplot(f, [a,b,c,d]) where a x b and c y d. The default configuration of this plotter function is ezplot(f) and the corresponding default domain is -2 x 2 and -2 y 2 . In the event that a = c and b = d, it suffices to write ezplot(f, [a,b]) For implicitly defined function f(x,y) ezplot(f, [a,b,c,d]) plots f(x,y) = 0 over the domain D = {( x, y ) : a x b, c y d } .
Example >> ezplot('cos(x^2 - y^2)',[-3,3,-4,4])

77

B) Parametric Plot A parametrically defined planar curve can be displayed in MATLAB using the plotter function ezplot. Thus, for any point (x,y) on the curve, if (t ) = ( x(t ), y (t )), t is a parametrization then ezplot(x,y, [,]) plots (x(t), y(t)) over the domain(parameter set) t . The default domain -2< x < 2 , i.e. ezplot(x,y) plots the expression (x, y) over the default domain -2< x < 2 .
Example

>> ezplot('sin(t)','cos(t)') >> grid

The graph of a function, y = f(x) of a single-variable x can be displayed in MATLAB using the function ezplot , the corresponding syntax is ezplot(f,[a,b]).
Example

>> ezplot('sinh(x)',[-3,3]) >> grid

78

C) Field Plot In MATLAB, we can display a vector quantity,

r = u i + vj

e.g. velocity of a wind, the

velocity of flow of a fluid etc, measured at uniformly spaced points in a two dimensional domain D. The plotter function used to display a vector field would exhibit an arrow at each data point (x,y), whose direction and magnitude corresponded to the value (u(x,y),v(x,y)). For two dimensional case, such a plot can be achieved with the built-in function quiver.
Example

Suppose f(x, y) = -yi + xj defined over the rectangle [2, 2] [-2,2]. To display the plot of the vector field, we write the following >> u=inline(-y,x,y) >> v=inline(x,x,y) >> x=linspace(-2,2,11); >> y=linspace(-2,2,11); >> [X,Y]=meshgrid(x,y); >> U=u(X,Y); V=v(X,Y); >> quiver (X,Y,U,V) >> axis image >> title(f(x,y)=-yi+xj)

79

If you do not care for the crowded appearance of the vectors, you can display/try the following lines of commands command, >> [x,y]=meshgrid(-2:0.2:2); >> U = -y; >> V = x ; >> quiver(x,y,u,v) >> title('r = -y i + x j') to get the following graphics with dense, i.e. larger number of arrows

80

D) Contour Plot In MATLAB, we can plot contour curves of a function, Z = f(x,y) of two variables. A contour plot is the level curves of Z corresponding to a given value. The first step is specifying the domain, i.e. range of values for x & y and generating grid of points, which can be done by using the meshgrid command on the given domain. We then, compute the function value at each point and finally use MATLAB's contour command to draw the level curves. The following lines of commands should produce the level curves of

f ( x, y ) = x e x y
2

On the domain D = {( x, y ) : 0 x 2, 2 y 2 }

>> [x,y] = meshgrid(0:.05:2, -2:.05:2); >> z = x .* exp(-x.^2 - y.^2); >> contour(x,y,z)

It is possible to label each contour (level curve) with its corresponding value, a constant value of the function. This can be achieved by rewriting the previous code (lines of commands) as follows >> [x,y] = meshgrid(0:.05:2, -2:.05:2); >> z = x .* exp(-x.^2 - y.^2); >> [t,h]=contour(x,y,z); >> clabel(t,h)
81

If you want to display exactly a given number of contours, you can specify the number, i.e. how many you want. All you need to do is, introduce a fourth argument to the function contour >> [x,y] = meshgrid(0:.05:2, -2:.05:2); >> z = x .* exp(-x.^2 - y.^2); >> contour(x,y,z,3)

82

2d Implicit Plotting Revisited

The MATLAB built-in function contour can also be used to display/plot the graph of a function defined implicitly. This can be demonstrated by the following example. Consider the equation 3 3 x + y = 3 xy

Often, an equation such as this one is difficult (or impossible) to solve for y in terms of x. However, one can use MATLAB function contour as an implicit function plotter, thereby ignoring the need to solve the equation explicitly for y in terms of x before plotting. We start by collecting all terms to one side of the equation so as to make the above equal to zero. 3 3 x + y 3xy = 0 Now, we set f ( x, y ) = x3 + y 3 3 xy The desired equation then reads f(x; y) = 0 Evidently, the graph of the implicit function is the level curve of f(x; y) = , where =0 i.e. a single level curve that can be displayed using the MATLAB function contour. To render comparison, we shall do this for the implicit function, cos( x 2 y 2) = 0 . >> [x,y] = meshgrid(-3:.05:3, -4:.05:4); >> z = cos(x.^2 - y.^2); >> contour(x,y,z,[0,0])

83

7.3 Three Dimensional Plotting


MATLAB supports display of graphics in three-dimensional space. Lines, points and surfaces can be visualized by use of MATLAB built-in functions.
A) Curves in 3d

One can display lines and points in 3d with a three-dimensional counterpart of the function plot. The MATLAB built-in function plot3 plots points and lines in 3d space. The syntax is plot(x,y,z), where x,y and z are arrays/vectors that have the same size/length. The command plot3(x,y,z), plots a line through the points whose coordinates in R3 are given by x, y and z. Observe here that the curve is given parametrically.
Example >> t=0:0.01:37; >> plot3(sin(t),cos(t),t) >> xlabel('x'),ylabel('y'),zlabel('z') >> title('Helix')

As with the built-in function for 2D case, plot the function for 3d, plot3 also has options to specify how a line/point should be plotted. This preference handled by introducing a fourth argument to the function, for instance we can change the color of the above helix to one of our choice, say magenta as follows >> plot3(sin(t),cos(t),t,'m' )

84

Line style can also be specified for the plot3 function while plotting a parametric curve over a domain D R3 .
B) Parametric curves in 3d

A parametrically defined space curve can also be visualized using the built-in function ezplot3, a 3d analogue of the parametric curve plotter function ezplot. Given any point (x,y,z) on the spatial curve, if (t ) = ( x(t ), y (t ), z (t )), t is a parametric representation then ezplot3(x(t), y(t), z(t), [,]) plots (x(t), y(t), z(t)) over the parameter set t . The command, ezplot3(x,y,z) plots the space curve over the default domain 0 < t < 2*pi, provided that t is declared a symbolic variable.
Example >> syms t >> ezplot3(t*sin(t),t*cos(t),t,[0,50],animate)

The last argument animate is used to produce animated trace of the given space curve.

85

7.4 Surface Plotting


One can create and display a three-dimensional graphics with MATLAB. The built-in function surf can be used to create the plot of a three-dimensional surface provided that a preferred domain and the corresponding grid points are furnished.
Example

>> [X,Y] = meshgrid(-2:0.2:2, -2:0.2:2); >> Z = X.*exp(-X.^2 - Y.^2); >> surf(X,Y,Z) >> title('z=xe^{-x^2-y^2}')

The MATLAB command surf(X,Y,Z ) plots the points on a grid of the appropriate size generated by the other built-in function meshgrid. The command [X Y] = meshgrid( x, y ); assigns X and Y two matrices, the first with the x values copied down the columns, and the second with the y values copied across the rows. In the above lines of commands keep all but replace the function surf by another function mesh and then see the change >> [x,y] = meshgrid(-2:0.2:2, -2:0.2:2); >> z = x.*exp(-x.^2 - y.^2); >> mesh(x,y,z) >> title('z=xe^{-x^2-y^2}') 86

If the MATLAB built-in function surfc is used instead of either surf or mesh we will have a surface with adds a contour plot over the domain in the xy-plane as can be seen below >> [x,y] = meshgrid(-2:0.2:2, -2:0.2:2); >> z = x.*exp(-x.^2 - y.^2); >> surfc(x,y,z) >> title('z=xe^{-x^2-y^2}')

87

Graphics in 3d, oftentimes represent real world data and hence contour plots usually permit physical interpretations. Thus, if a 3d surface is taken to be a topographic map of a mountain then the corresponding contours represent points of equal elevation/height, isobars or in case the surface represents a temperature distribution the contours represent isotherms, points of equal temperature. MATLAB can be used to visualize not only lines of identical value i.e. contours but also regions of similar value. The later is done by using the built-in function contourf, that gives colorings

Example

>> [x,y] = meshgrid(-2:0.2:2, -2:0.2:2); >> z = x.*exp(-x.^2 - y.^2); >> subplot(211) >> surfc(x,y,z) >> % >> subplot(223) >> contour(x,y,z) >> % >> subplot(224) >> contourf(x,y,z)

88

7.5 Importing MATLAB Graphics into Office Applications


Once a MATLAB graphics is generated we might want to insert it into a word document. The simplest way of transporting a graphics from MATLAB to a word document is by a copy-and-paste operation, a two step process. To this end, go to the Figure window, select the Edit menu and then choose Copy Figure.

This will send the figure into the Windows clipboard as an enhanced metafile, .emf format. Then, in the appropriate part of the MS Word document, position the cursor and choose Paste. The clipboard contents can then be pasted into the Word document.

89

Adjustment of size
It is possible that the pasted MATLAB graphics may not fit into the space available on your document. If this is the case, acceptable size can be adjusted by left clicking on the graphics as depicted below

and then selecting Format Picture and then in the Format Picture dialog pull down menu click size tab, finally select the right width/height.

90

Interpolation and Curve Fitting with MATLAB


Representing Polynomials

A polynomial can be described in MATLAB by storing all its coefficients in a vector, in descending order of the exponents.
Example: 1) p1(x) = x + 3 can be stored as p1 = [1, 3]; and 2) p2(x) = x2 - x - 2 can be stored as p2 = [1, -1 , -2];

A row vector of length n + 1 is understood in MATLAB, as a polynomial of degree n. We can evaluate a polynomial at a given point using the MATLAB built-in function polyval.
Example: The value of the second degree polynomial p2(x) = x2 - x - 2, after storage as a vector p2 = [1, -1 , -2] can be computed at 1 as follows.

>> a = polyval(p2,1) a= -2

91

The command roots also yields the zeros of the polynomial. >> r = roots(p2) r= 2 -1 We can multiply two polynomials. The product can be obtained by using of the command conv, convolution of their respective coefficients.
Example: The product of p1(x) = x+1 and p2(x) = x2 - x 2 can be found as,

>> p1= [1, 1]; >> p2= [1, -1, -2]; >> p = conv(p1,p2) p= 1 0 -3 -2

Here, p represents a polynomial of degree 3 given by p(x) = x3 - 3x 2. MATLAB allows evaluation not only of polynomials but also of an elementary (mathematical) function or an inline function (a user defined function to be used only during the current session) at a given point or at a given set of points. The corresponding syntax is feval('F',x) where F is the function name and x is a scalar (vector) argument.
Example:1) >> feval('cos',[0,pi/2,pi])

ans = 1.0000 0.0000 -1.0000 2) >> f = inline('x.*cos(x)'); >> feval(f,[-pi,pi/2,pi,2*pi]) ans = 3.1416 0.0000 -3.1416 6.2832

92

Curve Fitting

In MATLAB a curve can be fitted to a set of data points by the least square method with the restriction to polynomials. The built-in function ployfit interprets the best fit of a curve and fits a polynomial to a given set of data points. The command polyfit(x,y,n) determines the coefficients of a polynomial p(x) of degree n that fits into the data points, i.e. p(x(i)) = y(i) in a least-squares sense.
Example: In what follows, the function polyfit interprets the best fitting polynomial of the designated degree to the 11 data points given.

a)

>> x = 0:10; >> y = [0 1 4 9 16 25 36 49 64 81 100]; >> p = polyfit(x,y,2) p= 1.0000 0.0000 -0.0000

The output p = [1.0000 0.0000 -0.0000] is a row vector of coefficients of the best fitting polynomial of degree 2, namely p(x) = x2. Changing the third argument to 1 forces polyfit to return a polynomial of degree 1 that best fits into the same set of data points as follows. b) >> x=0:10; >> y=[0 1 4 9 16 25 36 49 64 81 100]; >> p=polyfit(x,y,1) p= 10.0000 -15.0000 In this case, the output is p = [10.0000 -15.0000] and hence p(x) = 10x 15.

93

References

Brian R. Hunt, Ronald L. Lipsman, J. Rosenberg, Kevin R. Coombes


A Guide to MATLAB: For Beginners and Experienced Users; Cambridge University Press (2006)

Stormy Attaway: Matlab:


A Practical Introduction to Programming and Problem Solving; Elsevier, INC. (2009)

Andrew Knight
Basics of MATLAB and Beyond; Chapman & Hall/CRC (2000)

Amos Gilat: MATLAB


An Introduction with Application; John Wiley & Sons, INC. (2008)

Tobin A. Driscoll Learning MATLAB; SIAM (2009) Kermit Sigmon, Timothy A. Davis
MATLAB Primer, Sixth Editio ; Chapman & Hall/CRC (2002)

94

You might also like