You are on page 1of 11

E26: Appendix A.

3: Introduction to MATLAB

Appendix A.3: Introduction to MATLAB


MATLAB is a sophisticated software package and we are only going to touch upon a few of its capabilities within this book. MATLAB is essentially a powerful programming language; one of the reasons that it is so powerful is that its basic data structure is the array. Therefore, you can solve problems that involve large vectors and matrices intuitively and manipulate the results easily. MATLAB is used in this book almost exclusively for carrying out numerical simulations. All of the examples in this book that use MATLAB were completed using MATLAB Version 7. These examples could be solved with little or no modifications using earlier versions of MATLAB. Additional information concerning MATLAB can be obtained from the distributor. MATLAB 7 The MathWorks, Inc. http://www.mathworks.com/ 1-508-647-7000

A.3.1 Getting Started


When you open MATLAB, you will be in the Command Window or working environment, as shown in Figure A.3-1. This is the set of tools and facilities that you work with as the MATLAB user or programmer. The working environment includes facilities for managing the variables in your workspace and importing and exporting data. There are also tools for developing, managing, debugging, and profiling M-files, which are MATLAB programs or applications. Notice the windows that show the Command History (the list of commands that you executed previously; these can be cut and pasted back into the Command Window to re-execute them) and the window which shows both the files in the current directory (Current Directory tab) and the variables currently in the workspace (Workspace tab). You can change the directory that you are working in from within the Current Directory tab. You can enter variables and manipulate them, call functions, etc. in the working environment. The commands are entered at the command-line prompt (>>). The best way for you to get started with MATLAB is to learn how to enter and manipulate matrices as these are the fundamental data type used by MATLAB. In MATLAB, a matrix is a rectangular array of numbers; special meaning is sometimes attached to 1-by-1 matrices (i.e., scalars) and to matrices with only one row or column (i.e., vectors). The operations in MATLAB are designed to be as natural as possible. Where other programming languages work with numbers one at a time, MATLAB allows you to work with entire matrices quickly and easily. Therefore, it is much easier to work with large sets of data (such as the temperature distribution predicted by a numerical simulation) in MATLAB.

E26-1

E26: Appendix A.3: Introduction to MATLAB

command window command-line prompt

to change current directory

Current Directory tab Command History

Figure A.3-1: MATLAB working environment

You can enter matrices into MATLAB in several different ways, including: o manually as an explicit list of elements, o as data loaded from an external file, o generated using functions built into MATLAB, or o generated with your own functions (i.e., your own M-files). To enter matrices manually, you have only to follow a few basic conventions: o separate the elements of a row with blanks or commas, o use a semicolon (;) to indicate the end of each row, and o surround the entire list of elements with square brackets, [ ]. For example, to enter the 3x3 matrix A , shown below:
2 3 1 A= 1 5 1 7 1 2

(A.3-1)

it would be necessary to type the following into the MATLAB environment.


>> A = [2 3 1; 1 5 1; 7 1 2]

Note that MATLAB will echo the results of carrying out each command as it is entered; in this case, MATLAB will display the A matrix that was created after you press the Enter key.

E26-2

E26: Appendix A.3: Introduction to MATLAB

A = 2 1 7 3 5 1 1 1 2

The echo can be turned off by using a semicolon after your command (the opposite of Maple where the semicolon requests an echo). For example, typing:
>> A = [2 3 1; 1 5 1; 7 1 2];

would not be echoed in the working environment. If you ever want to see what the MATLAB variable A is, just type A and press the Enter key:
>> A A = 2 1 7 3 5 1 1 1 2

The 3x1 vector b , defined as:


1 b= 2 5

(A.3-2)

may be entered as:


>> b = [1; 2; 5] b = 1 2 5

A.3.2 Working with Matrices


Working with matrices in MATLAB is extremely natural. For example, the solution to the matrix equation:
2 3 1 x1 1 1 5 1 x = 2 or A X = b 2 7 1 2 x3 5

(A.3-3)

E26-3

E26: Appendix A.3: Introduction to MATLAB is obtained simply by typing:


>> X=A\b X = 11.0000 6.0000 -39.0000

You can read more about the operation \ by typing:


>> help slash Matrix division. \ Backslash or left division. A\B is the matrix division of A into B, which is roughly the same as INV(A)*B , except it is computed in a different way. If A is an N-by-N matrix and B is a column vector..

MATLAB has an extensive help system that can be accessed either by typing help followed by the function you are interested in or by selecting MATLAB Help from the Help menu. To obtain help relative to the use of the exponential function:
>> help exp EXP Exponential. EXP(X) is the exponential of the elements of X, e to the X. For complex Z=X+i*Y, EXP(Z) = EXP(X)*(COS(Y)+i*SIN(Y)). See also expm1, log, log10, expm, expint. Overloaded functions or methods (ones with the same name in other directories) help sym/exp.m Reference page in Help browser doc exp

The details of the help message may differ depending on what version of MATLAB you are using; however, the specific capabilities of MATLAB that we will be using should be compatible with any version later than 5.0. Note that, unlike EES, variables in MATLAB are case-sensitive. Typically, we will be assigning or addressing the elements in a vector or array using subscripts. The element in row i and column j of matrix A is denoted by A(i,j). For example, A(2,1) is the number in the second row and first column; for matrix A in Eq. (A.3-1), A(2,1) is 1 and A(3,1) is 7. If you want to change the value of A(2,1) from 1 to 8, simply re-assign it:
>> A(2,1)=8; >> A A =

E26-4

E26: Appendix A.3: Introduction to MATLAB

2 8 7

3 5 1

1 1 2

It is possible to extract or manipulate entire rows or columns of a matrix. To obtain the 2nd column of A , use the : symbol which indicates all entries; therefore, A(:,2) would indicate all rows and column 2.
>> A(:,2) ans = 3 5 1

The mathematical operators +, -, *, / etc. have their typical meanings when applied to scalar arguments. However, if these (and any) operator is applied to a matrix then the operator will refer to the matrix form of the operation. For example, Ab is the matrix multiplication of the matrix A by the vector b (you may need to review your linear algebra to remember what this means):
>> A*b ans = 13 23 19

The order matters for matrix multiplication; that is b A will not be equal to Ab , in fact, b A is not even possible, as you cannot multiply a 3x1 matrix with a 3x3 matrix:
>> b*A ??? Error using ==> mtimes Inner matrix dimensions must agree.

You may want to avoid carrying out matrix operations and, instead, operate on each element in a matrix individually. This can be accomplished by placing a period (.) in front of the operator. For example, the operation A*A leads to the matrix multiplication of A by itself:
>> A*A ans = 35 63 36 22 50 28 7 15 12

E26-5

E26: Appendix A.3: Introduction to MATLAB whereas the operation A .*A leads to each element in A being squared.
>> A.*A ans = 4 64 49 9 25 1 1 1 4

The results are quite different and most beginners with MATLAB will forget that commands are interpreted according to operations on matrices.

A.3.3 Using M-Files


MATLAB is both a programming language and an interactive computational environment. The files that contain code in the MATLAB language are called M-files; the easiest way of developing a numerical solution is as an M-file because it can be saved, manipulated and debugged without having to be re-typed in each time. You create M-files using a text editor and then access them from the working environment as you would any other MATLAB function or command. There are two kinds of M-files: o Scripts, which do not accept input arguments or return output arguments. Scripts operate on data contained in the workspace and are exactly equivalent to typing commands directly into the workspace. o Functions, which can accept input arguments and return output arguments. Functions do not operate on the data in the workspace and can only access variables that are local to the function. The easiest way to create an M-file is to select File>New>M-file; this will open an M-file editor where you can enter the code and save the file for later use. You can save your M-files in any directory that makes sense. However, in order to run the file from the MATLAB environment you need to make sure that the file is located in a directory that is in MATLABs search path. To place a new directory in the search path, type the command pathtool and then click the Add Folder button in the Set Path dialog window that pops up (shown in Figure A.3-2 for MATLAB release 7) and navigate to the directory that you want to add.

E26-6

E26: Appendix A.3: Introduction to MATLAB

Figure A.3-2: Set Path dialog.

When you run a script, MATLAB simply executes the commands that are contained in the Mfile. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not formally return output arguments, any variables that they create remain in the workspace and can therefore be used in subsequent computations. In addition, scripts can produce graphical output using functions like plot. Functions are M-files that can accept input arguments and return output arguments. The name of the M-file and of the function should be the same. Functions operate on variables within their own workspace which is separate from the workspace at the MATLAB command prompt. Both types of M-files will be needed to generate numerical solutions to heat transfer problems. Open a new M-File and save it as practice.m in a directory that is contained in MATLABs search path. Comments can be used to clarify the code contained in M-files. Comments are indicated by the % symbol; anything following the % symbol is not executed. In your practice.m script, specify the radius and calculate the area of a disk:
r=2; %radius of disk A=pi*r^2; %area of disk

Save the file and execute it from the main workspace; nothing appears to happen but if you type r or A then you can see that these variables have been assigned.
>> practice >> A A = 12.5664

E26-7

E26: Appendix A.3: Introduction to MATLAB


>> r r = 2

One of the nice things about using MATLAB is that it is easy to debug as you go along; for example, if you were unsure as to the value of r in the script then simply remove the semicolon:
r=2 %radius of disk A=pi*r^2; %area of disk

and MATLAB will echo the value to the workspace as it executes the script.
>> practice r = 2

Scripts can be turned into functions. The header of the function has the format: function[output argument(s)]=function name(input argument(s)) The keyword function tells MATLAB that you are creating a function rather than a script. In MATLAB (unlike EES) more than one output argument can be returned from the function; these go in the square brackets. For example, our script practice.m can be turned into a function that takes r as an input and returns A as an output:
function[A]=practice(r) A=pi*r^2; %area of disk

You can call the function practice from any other function or the main workspace.
>> A=practice(1) A = 3.1416

It is important to understand that functions have their own workspace and only communicate with the calling workspace via the input/output protocol. For example, we could try to re-assign the input argument r within the function:
function[A]=practice(r) A=pi*r^2; r=5; %area of disk %attempt to re-assign r

Executing practice will not affect the value of r in the workspace. E26-8

E26: Appendix A.3: Introduction to MATLAB

>> r=1; >> A=practice(1); >> r r = 1

A.3.4 MATLAB Programming Constructs


MATLAB allows the use of programming constructs that should be familiar to anyone who has used a formal programming language like FORTRAN, Basic, etc. However, you may not be familiar with these other languages; this section introduces a few of the most commonly used logic statements. The if/else statements are very common and useful. These logic statements are used to conditionally execute a statement or set of statements based on an expression. For example, we could rewrite the practice.m function so that it returns the area of a disk if r<5 and otherwise it returns the value 999.
function[A]=practice(r) if(r<5) A=pi*r^2; else A=999; end

%area of disk

Note that the statements within the if and else statements are indented; this is good form and makes it very easy to understand the structure of the code. Execute the function practice from the workspace and check if it is working.
>> practice(1) ans = 3.1416 >> practice(6) ans = 999

Notice that the if statement is not followed by then as in most languages. Also, the relational operators are familiar with the exception of equality, which is indicated by = = rather than =; to see the list of relational operators (and other things) type help < in the workspace. Finally, dont forget that all of these programming constructs must be terminated with an end keyword.

E26-9

E26: Appendix A.3: Introduction to MATLAB The for loop is analogous to the DUPLICATE statement in EES; it executes a statement (or several statements) a specific number of times. It will not be possible to carry out numerical solutions to heat transfer problems without using a for loop. The for keyword is followed by an integer variable and a range; e.g., for i=1:10 statement(s) end would execute the statements sandwiched between for and end 10 times; each time the variable i would take on a different value. We can make the function practice return a 10x1 vector in which the first element is the input argument r and each subsequent element is twice the previous one:
function[A]=practice(r) A(1,1)=r; for i=2:10 A(i,1)=A(i-1,1)*2; end

You can execute practice from the command-line prompt:


>> practice(r) ans = 1 2 4 8 16 32 64 128 256 512

By nesting for loops you can generate or operate on matrices rather than vectors. Finally, the while statement repeats a set of statement until some break condition is met; often, the while statement is used to terminate an iteration process within a numerical method based on achieving convergence. Here we can rewrite the practice function so that it stops adding values to the vector when they get larger than 4000.
i=1; A(i,1)=r; while(A(i,1)<4000) i=i+1; A(i,1)=A(i-1,1)*2; end

E26-10

E26: Appendix A.3: Introduction to MATLAB

There are many other capabilities of MATLAB and we will introduce several additional aspects of the software in the context of various problems; however, this should be sufficient to get you started.

E26-11