APPENDIX I BASIC MATLAB (for Cytomechanists) (Adapted from Jon Dingwell) Introduction MATLAB is a software-based 'matrix laboratory' that is useful for analyzing biomechanical problems. Simulink is a subset of Matlab, that is a graphical method to set up a series of calculations, such as analog simulation of a controlled system, governed by differential equations. Tutorials for both Matlab and simulink are on-screen in the program. Command line The first line (>>) you see when you start up MATLAB is the command window . Commands typed in this window are executed immediately. MATLAB programs ‘.M’Files) can be run from the command line by typing their name UNIX commands can be invoked from >> by prefacing them with a !. An important UNIX command is '!ls' to see what files you have saved. Another command is !pico, which calls a UNIX editor for creating programs. Pico has a menu bar at the bottom for help with saving and reading files. There are several MATLAB commands that are best used interactively from the Command window. These can be executed by typing them in at the command line prompt ('>>') in the MATLAB Command window : help 'help' by itself will provide an index . 'help' followed by the name of any command will list the syntax and use of that command. demo Runs the MATLAB demo program pwd 'Print Working Directory' - prints the directory (or folder) that you are currently working in. cd 'Change Directory' - changes the current working directory. (Notes: (1) 'cd ..' goes back one directory level, (2) directories on PC machines are separated by back-slashes (\), and folders on Mac machines are separated by colons(:)). dir Prints a list of all of the files located in the current working directory. what Prints a list of all the executable MATLAB files (M-Files) in the current working directory. whos Prints a listing of all the variables currently in MATLAB memory. clear Clears variables from memory. 'clear' or 'clear all' clears all variables from memory. 'clear' followed by the name of any variable will clear only that variable from memory. clc 'Clear Command Window' - clears all of the text in the command window and resets the command prompt at the top of the screen. simulink this gets you into that specialized program. For example: >> pwd will give the following output: >> pwd ans = C:\MATLAB\bin Use of Semi-Colons: Typing a semi-colon at the end of a line hides the output of that statement. example, the following two commands produce the following two outputs: For >> pwd; >> >> pwd ans = C:\MATLAB\bin >> This will be important to remember when you start writing MATLAB programs, where you will be executing many statements in a row, and do not want to see the output of each one of them, one at a time. Interactive use versus stored Files: Executing commands one at a time in the Command window not convenient when analyzing large data sets, or performing multiple operations on multiple files of data. For these, a MATLAB program (also called an M-File, because it is followed by an extension '*.m') can be written that could run all at once. An M-File is merely a collection of MATLAB commands, which are executed in order when the program is executed from the Command window. Many of MATLAB's built in features and functions are merely M-Files themselves, and these M-Files (and your M-Files) are all executed in the same way, simply by typing the name of the file at the prompt in the Command window without the '.m' extension (e.g. to execute a program called testcalc.m, simply type 'testcalc' at the Command prompt). To create a new M-File in MATLAB, go to the 'file' menu at the top of the Pico screen and select 'new'. This will open a new window, called the editor window. MATLAB commands can be typed in this window just as they would be in the Command window, except that they are not executed. When the M-File is saved and then executed from the Command window, all of the commands in the M-File are executed by MATLAB in the order in which they are typed. Commenting Your Code: Comments are statements which are typed into your program code, but which are not executed by MATLAB. You can (and should!) comment your code liberally. In MATLAB, comment statements are designated by a percent sign (%). Matlab will ignore any text following a '%' on a given line. Comments are an excellent way for you and others to keep track of what you are trying to do in a program. It is useful to put comments at the beginning of a program, that should include the name of the M-File, who wrote it and when, a brief description of what the program does, and a list of the variable names used in the program and their descriptions. Comments should also be made throughout the program to let the reader know what the program is doing at each step. Working With Matrices: Generating Matrices One way to generate matrices is to import (or 'load') data from an external file, and this will be covered later. For now, just enter in from the keyboard a couple of small matrices (or vectors, which are simply matrices with only a single row or column of values). Matrices can be entered explicitly by typing the values directly into your program. In this case, the matrix is denoted by square brackets, [...]. The elements on a single row are separated by spaces or by commas, and semi-colons separate rows. For example, the statements: >> A = [1 2 3; 4 5 6; 7 8 9]; and >> A = [1, 2, 3; 4, 5, 6; 7, 8, 9]; and >> A = [1,2,3 4,5,6 7,8,9]; will all produce the following 3x3 matrix: A = 1 2 3 4 5 6 7 8 9 Matrix elements can be any MATLAB expression, and need not be simply numbers. For example, the following statement: >> A = [-1.3, sqrt(3), (1+2+3)*4/5]; produces the following 1x3 matrix: A = [-1.300 1.7321 4.8000] There are also several types of specialized matrices, which MATLAB will generate for you. Two such matrices are the 'magic' matrix and the 'rand' (or "random") matrix. Type 'help magic' or 'help rand' at the Command prompt to find out more. These commands are an easy way to generate example matrices to use if you want to play around with MATLAB's various matrix manipulation features. You can also generate a vector (single row matrix) of numbers using a single command, providing a starting number, and increment, and an ending number, as follows: >> A = 0:2:10; %-- "Let A go from 0 to 10 in steps of 2" --% produces the following 1x6 matrix: A = [0 2 4 6 8 10] Index Syntax The elements of matrices in MATLAB are denoted by their row and column indices, i.e. 'A(i,j)' refers to the element in row i and column j of matrix A. One can also refer to a block of rows or columns at a given time, by using the MATLAB colon (:) notation, i.e. 'A(i:j,k:l)' refers to the elements between rows i and j, and between columns k and l of matrix A. Typing a colon by itself will designate all of the rows (or all of the columns) in that matrix, i.e. 'A(i:j,:)' refers to all of the columns between rows i and j of matrix A, and 'A(:,k:l)' refers to all of the rows between columns k and l of matrix A. To start, let's generate a 5 x 5 "magic square" matrix: >> A = magic(5); This will produce the following 5x5 matrix: A = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 The following statements shown on the left, will produce the following matrices shown on the right: >> B = A(2,4); gives: B = [14] >> C = A(3,2:4); gives: C = [6 13 20] >> D = A(3,:); gives: D = [4 6 13 20 22] >> E = A(1:3,4); gives: 8 E = 14 20 >> F = A(2:4,:); gives: 23 5 7 14 16 F = 4 6 13 20 22 10 12 19 21 3 Addition and Subtraction Matrices of the same size (i.e. same number of rows and columns) can be added and subtracted like any two numbers. This will result in an element-by-element addition or subtraction of the two matrices. The following example shows how this is done: >> >> >> >> A B C D = = = = [1 2; 4 5; 7 8]; [2 3; 5 6; 8 9]; B + A; B - A; This will produce the following 3x2 matrices: A 1 2 4 5 7 8 = B = 2 3 5 6 8 9 C = 3 5 9 11 15 17 D = 1 1 1 1 1 1 Multiplication and Division of Matrices and Arrays Multiplication of matrices and arrays in MATLAB is somewhat more complicated. any matrix or array can be multiplied by a scalar (a single number). This will result in every element of that matrix being multiplied by that scalar. The following is an example: >> A = [1 2; 4 5; 7 8]; >> B = 5 * A; This will produce the following 3x2 matrices: A 1 2 4 5 7 8 = B = 5 10 20 25 35 40 Using the '*' symbol by itself to multiply two matrices denotes matrix multiplication. Matrix multiplication will only work if the inner dimensions of the two matrices are the same, (i.e. if the number of columns in the first matrix is the same as the number of rows in the second). In order to multiply two matrices of the same size in an element-by-element manner, you must perform "array multiplication" which is done using the '.*' notation. Division of matrices and arrays works in much the same way, using '/' and './'. To clear this up a bit, the following two square matrices can be multiplied using either matrix multiplication or array multiplication, as follows: >> >> >> >> A B C D = = = = [1 2 3; 4 5 6; 7 8 9]; [3 2 1; 6 5 4; 9 8 7]; B * A; B .* A; This will produce the following 3x3 matrices: A = 1 2 3 4 5 6 7 8 9 B = 3 2 1 6 5 4 9 8 7 18 24 30 = 54 69 84 90 114 138 C 3 4 3 D = 24 25 24 63 64 63 2D Graphics: MATLAB has several graphing functions, a few of which are listed: figure Assigns a specific figure number to the current figure. This is not necessary, but is often useful for keeping track of large numbers of figures plot Plots the data in the statement. E.g. 'plot(x,y)' will plot a vector defined by x on the horizontal axis, and the values given in vector y on the vertical axis. gplot gplot(Madj,Mpos) Displays the 2-D graph defined by adjacency (or connectivity) matrix and node position matrix . subplot Defines a set of subplots, such that multiple plots can be drawn in the same figure window. E.g. 'subplot(m,n,a)' defines a subplotting scheme with m by n subplots within a given figure, and specifies the current plot as number a. See the first assignment handout for an example of subplotting. title Puts a title on the current figure (e.g. 'title('This is My Title')'). xlabel Puts a title on the x-axis of the current figure (e.g. 'xlabel('X-axis Data')'). ylabel Puts a title on the y-axis of the current figure (e.g. 'ylabel('Y-axis Data')'). axis Defines the axis limits for the current figure (e.g. 'axis([0,10,100,100])' will draw a graph with x-axis values from 0 to 10, and y-axis values from -100 to +100). If you do not assign these explicitly, MATLAB will default to axis limits sufficient for displaying all of your data. Example 1: Solving Truss Forces (Sparse matrices) MATLAB is stingy with memory usage and likes to conserve whenever possible. Large matrices can be memory 'hogs' and therefore require special handling. Many matrices are mostly filled with zeroes: these are called 'sparse'. Non-zero entries represent fewer than 5% of the total elements in a sparse matrix. An example of a sparse matrix is drawn from the equilibrium equations of a truss, as shown below: FL1 4 2 F8 6 F4 F1 F7 F3 F5 F2 1 FL2 F9 F11 F10 F6 3 5 F12 F13 8 7 One way to represent the equilibrium equations is as a matrix, where a=sin 45=cos45, as written (partially) below: (Note that the external loads are placed in a separate matrix) Joint 2 Joint 2 Joint 3 Joint 3 Etc. Joint 8 Fx Fy Fx Fy F1 -a -a 0 0 F2 0 0 -1 0 F3 0 -1 0 1 F4 1 0 0 0 F5 a -a 0 0 F6 0 0 1 0 F7 0 0 0 0 F8 0 0 0 0 F9 0 0 0 0 F10 0 0 0 0 F11 0 0 0 0 F12 0 0 0 0 F13 0 0 0 0 Fx 0 0 0 0 0 0 0 0 0 0 0 -a -1 So the matrix, A , above, represents the summation of all internal forces on the truss. For example, for joint #2, if you make force to the right positive: Fx = -aF1 + F4 + aF5 = 0 Similar equations can be written for the other joints, and it winds up with a problem having 13 unknowns with 13 equations (Count them). The external loads comprise a separate matrix, B. Given values, FL1= 5 N and FL2 = 1 N , B = [0 0 5 0 0 0 0 0 0 0 1 0 0] To indicate to MATLAB that A and B are sparse (this helps the memory) after you type in the entire matrix, you invoke the 'sparse' command: S=sparse(A) B= sparse(B) Solving for all forces is now easy for MATLAB, using the 'forward slash' symbol for factoring the 2 matrices: F = S\B With this command, you now have all 13 forces. To get them, all you have to do is ask, for example, type: F(1) = This should give you the value of F1, and so on for all the other forces. If you wanted the horizontal force at joint one, type 2 lines: Fleft= a* F(1) + F(2) Fleft = Drawing a Truss One way to create a sparse matrix is with the 'spalloc' command: M = spalloc(m,n,int) This allocates memory for an intially zero mXn sparse matrix which will hold at most int non-zero entries. For example, to draw a partial truss, the following program should work: %Partial truss drawing C = spalloc(4,4,13) ; % Connectivity matrix C(1,2) = 1; % I.e. member 1 is connected between joints 1&2 C(1,3) = 2; C(2,3)=3; C(2,4)=4; xy= [0.0,0.0 1.0,1.0 1.0,0.0 2.0,1.0]; gplot(C,xy); axis(‘equal’) Note that gplot relates the members and coordinates as depicted below: 0 0 0 0 1 0 0 0 (Coordinates 0,0) 2 (Coordinates 1,1) 3 (Coordinates 1,0) 0 0 0 4 (Coordinates 2,1) 0 0 Your drawing should look something like this: 1.0 0 0 1.0 2.0 Common Flow Control Commands (Used mostly in M-File Programs): These commands ('for' loops, 'while' loops, and 'if' statements) are common to any of the major programming languages, and are no different in MATLAB. The specific syntax may vary from language to language, but they function in the same way. for Begins a 'for' loop which executes the statements inside that loop a specified number of times (e.g. for i = 1:4 executes the loop 4 times). while Begins a 'while' loop. 'while' is always followed by a comparison, just like an 'fi' statement (e.g. 'while A <> B'). The statements inside this loop will be executed as long as the comparison in the 'while' statement is true. if 'if' is always followed by a comparison statement (e.g. 'if A==3', where the two '=' signs designates an "equality", whereas a single '=' sign designates an assignment). If the statement following 'if' is true, then the commands listed afterward are executed. If it is false, they are ignored. elseif 'elseif' comes after an 'if' statement, and will make a second comparison if the first comparison is not true. else 'else' is not followed by any comparisons, and will execute all of the enclosed statements if the preceding comparison(s) are all not true. end This will terminate any 'if', 'for', or 'while' loop series. Some examples of these structures are shown below. See the on-line help and MATLAB manuals for more examples: For Loop: for i = 1:m for j = 1:n A(i,j) = 1/(i+j-1); end end While Loop: while i < m A(i,1) = i.*m; m = m-1; end If statements: for i = 1:100 if i < 25 B(1,i) = 2 .* elseif (i >= 25) B(1,i) = 3 .* else B(1,i) = 5 .* end end i; & (i < 65) (i-2); (i+2) - 3; Commands for Dealing with ASCII Data Files: These commands ('load' 'save', and 'eval') are specific to MATLAB for dealing with tab-delimited ASCII text files. There are many commands available also to deal with binary data files, but these will not be discussed here. load 'load', followed by the name of a data file (e.g. 'load data.dat;') will load the data in that data file into a matrix of numbers with the same name as the data file (e.g. in a matrix called 'data'). The file must be a tab-delimited ASCII text file, containing only numbers (no text!), or MATLAB will choke on it. save Saves the data in a matrix to a specified data file. For example, the statement 'save output.dat A -ascii -tabs;' will save the matrix A in a file called "output.dat" as a tab-delimited ASCII text file. eliminating the '-ascii -tabs' part of the statement will cause the file to be saved as a MATLAB Binary file. (See on-line help for more info). eval "Evaluates" the text within the enclosed string as though it were a MATLAB command. This command is useful for writing programs, which need to read in multiple data files where each file has a different name. A text string is generated containing a 'load' statement and the name of each data file, and then this string is "evaluated" by 'eval' to load the file. An example of this is given in the program given with the first MATLAB assignment. (Also see on-line help for more info). The following statements illustrate the use of the 'eval' and 'load' functions in reading a set of four data files called 'data1.dat', 'data2.dat', 'data3.dat', and 'data4.dat'. Each data file is loaded and analyzed during one iteration of the 'for' loop. for TrialNum = 1:4 %-- Define a string variable, fn, which contains the name of each --% %-- data file. 'int2str' converts the value in TrialNum from an --% %-- integer format to a string format. --% fn = ['data', int2str(TrialNum)]; %-- Load each data file into the matrix 'VData'. The part in the --% %-- square brackets, [...], is the string that defines the command --% %-- that the 'eval' function will evaluate. These data will be --% %-- in a matrix whose name is defined by 'fn' (e.g. 'Data1') --% eval(['load ', fn, '.dat;']); %-- Store the loaded data matrix in a matrix called 'VData' --% eval(['VData = ', fn, ';']); %-- Clear the original data matrix with the name defined by 'fn' --% eval(['clear ', fn, ';']); end %-- end of the 'for' loop --% Simulink Quick Reference Block Name Important Sources Constant Sine Wave Pulse Generator Signal Generator Step White Noise Description Injects an input to the attached block Injects a constant value Injects a sine wave Injects a rectangular pulse Injects waves of selected forms Injects one rectangular edge Injects random noise Important Sinks Graph Scope Kitchen Plots output, axes, and permits printing Same as oscilloscope (WYSIWYG) (Not available in this version) Important Operators Discrete Integrator Time-limited Integrator Linear Derivative Gain Dot Product Integrator Summer Non-Linear Function Logical Operator Product Quantizer Limiter Integrator Transport Delay Switch Place equation in block AND, OR, NOR Analog Low Pass Analog High Pass Analog Band Pass Removes high frequencies Removes low frequencies Passes only in the middle (selected) Quantize the input in given intervals Integrate over a specified region Delay input by a specified amount of time Switch between two inputs Filters Analyzers Average PSD Example 1. Modelling viscoelasticity