Sie sind auf Seite 1von 34

BTE 4225 Computer Simulation In Biological Systems

Dr. Ibrahim Ali Noorbatcha

DEPARTMENT OF BIOTECHNOLOGY ENGINEERING IIUM

BTE 4225

MATLAB stands for Matrix Laboratory. It is a highperformance numerical computation, matrix manipulation, signal processing and visualization software. MATLAB integrates matrix computation, numerical analysis, signal processing, data analysis, and graphics in an easy to use environment where problems and solutions are expressed just as they are written mathematically -- without traditional programming.

MATLAB also features a family of applicationspecific solutions called toolboxes. Toolboxes are libraries of MATLAB functions that customise MATLAB for solving particular classes of problems. As an example we have the statistics toolboxes in the GIS computer laboratory. The statistics toolbox is a collection of over 100 MATLAB functions for descriptive, inferential and graphical statistics and linear models. It provides statistical data analysis, modelling and Monte Carlo simulation.

BTE 4225

Starting Matlab
Matlab for Windows Version 6.5.1 is used for all the examples in this handout. To start Matlab, select "programs" from the "start" button, go to Matlab menu set, select "Matlab" and click on it with left mouse button. To quit Matlab simply type quit <return>. The symbol <return> is used throughout the text to denote pressing the return or enter key. Boldface characters denote both text to be typed and matrices. The context will indicate specific use. Learning MATLAB Learning MATLAB is just like learning how to drive a car. You can learn all the rules but to become a good driver you have to get out on the road and drive. The easiest and best way to learn MATLAB is to use MATLAB.

BTE 4225

The >> is called the command prompt, and there will be a blinking cursor right after it waiting for you to type something.

BTE 4225

MATLAB executes the command you typed in, then prints out the result. It then prints out another command prompt and waits for you to enter another command. In this way, you can interactively enter as many commands to MATLAB as you want.

Type date and enter In the MATLAB command window, if you want to clear away all the visible text and have the cursor move to the top of the window, then type clc at the command prompt. To exit MATLAB, simply click the mouse on the File menu of the MATLAB command window and then select "Exit MATLAB" (alternatively, you could just enter quit at the MATLAB command prompt).

BTE 4225

Do the following:
1- 5+11 2-5*11+6

3-(6+6)/3

BTE 4225

4-9^3 5-5+9 enter 6-ans 7-ans+9 8- a=10 c=20 The _average=(a+b+c)/3 b=19

2) The Command Line and Basic Commands

BTE 4225

You can exit Matlab with the command exit or quit. On a UNIX system system, you may enter Matlab with the command: >> matlab and exit it with the command: >> quit It is advisable to have at least two open windows, one for Matlab and one for doing other tasks. Information about any command is available by typing: >> help command If you don't know the command you can view a listing of primary help topics simply by typing: >> help Exercises Matlab can be used as a pocket calculator. Switch on Matlab and try >> 2 + 3 to find out the result. You can also store values in variables. For example, try >> help = 6 and afterwards, look at the result of >> help + 2 Now, assign the value 2.20371 to the variable RM: >> RM = 3.76 and compute 5 * RM. What is the result? Finally, test the standard help-command (see above) to produce a listing of primary help topics.

BTE 4225

Once Matlab is started the Command Window appears as shown in figure. The command line with the prompt appears inside this Window. Type your command and press Return. Matlab will interpret and execute your command. The command line is the heart of using Matlab. All commands are entered at the command line, from adding two numbers, to executing programs (script files) and functions, or making graphs. First consider how the command prompt can be used as if it was a hand calculator. To add two numbers, for example 5+7 enter the following at the command prompt: 5+7 <return>

BTE 4225

The answer pops out and is declared as the variable ans. If a variable name is not declared explicitly (such as c=5+7), Matlab always names the output ans. Hence, the latest results write over the previous contents of ans. Next press the up arrow key and notice that the previous command comes up on the command line. Successive pressing of the up arrow displays earlier commands sequentially. Now type ans <return>. The number 12 should come up on the screen.

BTE 4225

The basic commands for scalars are as follows: + addition \ left division - subtraction ' transpose * multiplication ^ power / division Entering calculations has the same precedence or order of evaluation as other languages. This means that commands are evaluated left to right with parenthesis with the highest precedence. For example lets say that you wanted to multiply 3 by 4 add 5 to that then divide by 6 + 4 and then divide all that by 2. This would be entered as follows: (3*4+5)/(6+4)/2 <return>

BTE 4225

BTE 4225

Comments and the help function The % symbol indicates that the rest of the line is a comment; Matlab will ignore the rest of the line. However, the first few comments lines, which document the M-file, are available to the on-line help facility and will be displayed if, in this case, help stat

Built-in Functions
Certain Matlab functions operate essentially on scalars, but operate element-wise when applied to a matrix. The most common such functions are: sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, exp, log(natural log), rem(remainder), abs, sqrt sign, round, floor, ceil Try to compute the sine of pi (which is 'pi' in Matlab) but also check what the sine of the vector v=[pi/2, pi] is.

BTE 4225

(3*4+5)/(6+4)/2 <return> There are various other functions such as: sin --> sine cos --> cosine tan --> tangent exp --> exponential log --> natural log abs --> absolute value There are many other functions available in Matlab. For example, to take the sin of pi/2 type sin(pi/2) <return> where pi is already defined as 3.1416. Next, instead of adding 5+7 lets two variables a+b where a=5, and b=7. First declare variables a and b, by typing a=5 <return> b=7 <return> a+b <return>

BTE 4225

Listing Currently Defined Variables and Clearing Variables

Let's say you have defined a lot of different variables. You probably can't remember all the variable names you have defined, and so it would be nice to get a list of all the variables currently defined. This is exactly what the whos command does. Simply typing whos at the command prompt will return to you the names of all variables that are currently defined. For example: clear % clear variables from memory

BTE 4225

BTE 4225

- see notes below Grand total is 2 elements using 16 bytes Once you are done with the variables that you have defined how do you remove them from memory? This is exactly what the clear command is for. Typing clear at the command prompt will remove all variables and values that were stored up to that point.

Relations

The relational operators, with which Boolean expressions can be made, are < less than > greater than <= less than or equal >= greater than or equal == equal ~= not equal Note that "=" is used in an assigment statement while "==" is used in a relation. Relations may be connected or quantified by the logical operators: & and | or ~ not

BTE 4225

Suppressing Results with Semicolons Semicolons typed after commands can be used to hide the printing out of results. If you type an expression (such as "b = 4 + 5") and then follow it with a semicolon, then MATLAB will evaluate the expression and store the result internally, but it will not print out the results in the MATLAB command window for you to see. For example: A=5; B=10: C=15; D=20 The_average=(A+B+C+D)/4

BTE 4225

Variable Names and Assigning Strings to Variables There are some specific rules for what you can name your variables, so you have to be careful. - Only use primary alphabetic characters (i.e., "AZ"), numbers, and the underscore character (i.e., "_") in your variable names. You cannot have any spaces in your variable names, so, for example, using "this is a variable" as a variable name is not allowed, but "this_is_a_variable" is fine (in general, you can use the "_" character wherever you would use space to string words together in your variable name).

BTE 4225

MATLAB is case sensitive. What this means for variables is that the same text, with different mixes of capital and small case letters, will not be the same variables in MATLAB. For example, "A_VaRIAbLe", "a_variable", "A_VARIABLE", and "A_variablE" would all be considered distinct variables in MATLAB. You can also assign pieces of text to variables, not just numbers. You do this using single quotes (not double quotes --- single quotes and double quotes have different uses in MATLAB) around the text you want to assign to a variable. For example: some_text = 'This is some text assigned to a variable!'; some_text

BTE 4225

If you wish the variable c to equal a+b type c=a+b <return>. More complicated expressions can be written; for example c=(sin((a^2*b/tan(a)-b^2)/pi)*exp(a-b))/b. Matlab is case sensitive so the variables a and A, are considered as two different variables. Type who <return> A list of your variables in the workspace appears: a,b,c, and ans. The workspace represents which variables have been defined and are available for further calculations, manipulation or graphing. Now type whos <return>. The command whos does the same as who, but in addition it will tell you how many elements are in each variable, for example the variables a,b,and c are scalars so there size is 1 by 1 with one element. If a was a column vector with 10 elements then its size would be 10 by 1.

BTE 4225

MATLAB, the MATrix LABoratory


Three fundamental concepts in MATLAB, and in linear algebra, are scalars, vectors and matrices. A scalar is simply just a fancy word for a number (a single value). A vector is an ordered list of numbers (onedimensional). In MATLAB they can be represented as a row-vector or a column-vector. A matrix is a rectangular array of numbers (multidimensional). In MATLAB, a two-dimensional matrix is defined by its number of rows and columns. In MATLAB, and in linear algebra, numeric objects can be categorized simply as matrix. All calculations in MATLAB are done with "matrices". Hence the name MATrix LABoratory.

BTE 4225

BTE 4225

Creating Matrices in MATLAB In MATLAB matricies are defined inside a pair of square braces ([]). Punctuation marks of a comma (,), and semicolon (;) are used as a row separator and column separator, respectfully. Note: you can also use a space as a row separator, and a carriage return (the enter key) as a column separator as well.

my_scalar = 3.1415 my_vector1 = [2, 6, 8] my_vector2 = [2; 6; 8] how do we create a matrix called my_matrix with the numbers 8, 12, and 19 in the first row, 7, 3, 2 in the second row, 12, 4, 23 in the third row, and 8, 1, 1, in the fourth row? my_matrix = [8, 12, 19; 7, 3, 2; 12, 4, 23; 8, 1, 1]

combine different vectors and matrices together


BTE 4225

row_vector1 = [1 2 3] row_vector2 = [3 2 1] matrix_from_row_vec = [row_vector1 ; row_vector2] column_vector1 = [1;3] column_vector2 = [2;8] matrix_from_col_vec = [column_vector1 column_vector2] my_matrix = [8, 12, 19; 7, 3, 2; 12, 4, 23; 8, 1, 1] combined_matrix = [my_matrix, my_matrix]

The variables in the workspace can be saved to a file for future use. Matlab can save either all the variables in the workspace or selected variables. Before saving any variables to the disk type pwd <return>. The command pwd (print working directory) will indicate the location (drive and directory) to which the variables will be saved. To save any variables to a floppy disk type cd a: <return>. Next use the pwd command to check that the floppy drive a: has been properly set. Finally to save all the variables in the entire workspace type save fl_test <return> where fl_test is the filename that the variables are stored and fl are your first and last initials. Note that between fl and test there is an underscore.

BTE 4225

The save command creates the file fl_test.mat in the current directory. If you like to save only certain variables just type the variables you wish to save after the filename, for example to save the variables a and b type save fl_test2 a b <return>. If you desire to save data in ASCII then type save fl_test3.dat a -ascii <return>. All data are stored contiguously in the ASCII version. You can not separate data for different variables in a file saved as ASCII.

BTE 4225

3) Script Files and Functions

Most of Matlabs usefulness is in its wide variety of built-in functions. Some of these are in the computing engine of Matlab. For example sin and exp are such functions. Others are developed as files that can be called by a Matlab command with a statement of the form: [outputs] = functionname(arguments) where functionname is the functions name and arguments are the inputs to the function. A function can have one or many arguments. The results (outputs) returned by a function are listed on the left side of the = sign, in square brackets ([]). For example [V,D] = eig(X)

BTE 4225

A script file can be thought of as a program. It contains a series of commands or function calls. The difference between a function and a script file is that a function usually requires input arguments and will return only the output values. Just like a subroutine in Fortran or C, the variables used in a function are local. A script file requires any variables it needs defined within the workspace at the time of its use. Also a script file will return (to the workspace) every value it calculates. Script files are a simple way of writing programs and prototyping functions. They can be understood better through a simple example.

BTE 4225

The following steps will outline how to create a script file. From the Matlab command window point the mouse to the pull down menu File, then click on New, and finally click on M-file. A window with an editor should pop up. The screen should appear as follows (the actual window sizes vary and often they would overlap, this picture is arranged to show you both screens):

BTE 4225

BTE 4225

Move to the editor screen and type the following: a=5 b=7 c=9; d=sqrt(a^2+b^2+c^2) Click on the pull down menu File of the Editor/Debugger window. Click on Save or Save-As. Under the Drives title choose the drive and folder (for example A:/). Lastly, under File Name: write fl_first.m. 1. Go back to the Matlab window and type fl_first <return>. DO NOT TYPE the extension ".m", otherwise you will get an error. The variables a,b and d with there corresponding values should scroll through the screen. If you get an error, probably the drive location is not set correctly.

BTE 4225

1. Use pwd to check the drive, and if not set on drive A use the cd command to go to drive A. Notice that variable c did not appear on the screen. This is because a semicolon follows the declaration of c in the script file fl_first.m. A semicolon will prevent any values assigned on that line from being displayed on the screen. If one of the variables was not declared in the script file, it would have to be declared in the workspace for the program to run. 2. To investigate this, edit the file fl_first.m by removing the line b=7. 3. Run fl_first.m again in the Matlab command window. You should get an error. 4. Now type b=7 in the Matlab command window and press return. 5. Run fl_first.m again. You should get the correct value of d on the screen.

BTE 4225

Now develop a function to do the same task. It should have 3 inputs (x, y, z) and one output (q). When values or variables for x, y, and z are entered, the function should calculate q and rename it as the variable named in brackets. Go to the editor window and type: function [q]= fl_firstfn(x, y, z) q=sqrt(x^2+y^2+z^2) and save the function as fl_firstfn.m. Go back to the Command window and enter a=5, b=7, and c=7 by using proper procedure. Now type: [d]=fl_firstfn(a, b, c) The screen should show: q = 12.4499 d = 12.4499.

BTE 4225