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.
demoRuns 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(:)).
dirPrints a list of all of the files located in the current working directory.
whatPrints a list of all the executable Matlab files (M-Files) in the current working directory.
whosPrints a listing of all the variables currently in Matlab memory.
clearClears 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.
simulinkthis 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. For example, the following two commands produce the following two outputs:
> 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:
1 2 3
A = 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:
17 24 1 8 15
23 5 7 14 16
A = 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]
8
> E = A(1:3,4);gives:E = 14
20
23 5 7 14 16
> F = A(2:4,:);gives: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 = [1 2; 4 5; 7 8];
> B = [2 3; 5 6; 8 9];
> C = B + A;
> D = B - A;
This will produce the following 3x2 matrices:
1 2 2 3 3 5 1 1
A = 4 5 B = 5 6 C = 9 11 D = 1 1
7 8 8 9 15 17 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:
1 2 5 10
A = 4 5 B = 20 25
7 8 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 = [1 2 3; 4 5 6; 7 8 9];
> B = [3 2 1; 6 5 4; 9 8 7];
> C = B * A;
> D = B .* A;
This will produce the following 3x3 matrices:
1 2 3 3 2 1 18 24 30 3 4 3
A = 4 5 6 B = 6 5 4 C = 54 69 84 D = 24 25 24 7 8 9 9 8 7 90 114 138 63 64 63
2D Graphics:
Matlab has several graphing functions, a few of which are listed:
figureAssigns a specific figure number to the current figure. This is not necessary, but is often useful for keeping track of large numbers of figures
plotPlots 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.
subplotDefines 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.
titlePuts a title on the current figure (e.g. 'title('This is My Title')').
xlabelPuts a title on the x-axis of the current figure (e.g. 'xlabel('X-axis Data')').
ylabelPuts a title on the y-axis of the current figure (e.g. 'ylabel('Y-axis Data')').
axisDefines 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:
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)
F1 / F2 / F3 / F4 / F5 / F6 / F7 / F8 / F9 / F10 / F11 / F12 / F13Joint 2 / Fx / -a / 0 / 0 / 1 / a / 0 / 0 / 0 / 0 / 0 / 0 / 0 / 0
Joint 2 / Fy / -a / 0 / -1 / 0 / -a / 0 / 0 / 0 / 0 / 0 / 0 / 0 / 0
Joint 3 / Fx / 0 / -1 / 0 / 0 / 0 / 1 / 0 / 0 / 0 / 0 / 0 / 0 / 0
Joint 3 / Fy / 0 / 0 / 1 / 0 / 0 / 0 / 0 / 0 / 0 / 0 / 0 / 0 / 0
Etc.
Joint 8 / 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 / 1 (Coordinates 0,0) / 2 (Coordinates 1,1) / 00 / 0 / 3 (Coordinates 1,0) / 4 (Coordinates 2,1)
0 / 0 / 0 / 0
0 / 0 / 0 / 0
Your drawing should look something like this:
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.
forBegins 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).
whileBegins 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.
endThis 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 .* i;
elseif (i >= 25) & (i < 65)
B(1,i) = 3 .* (i-2);
else
B(1,i) = 5 .* (i+2) - 3;
end
end
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.
saveSaves 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 / DescriptionImportant Sources / Injects an input to the attached block
Constant / Injects a constant value
Sine Wave / Injects a sine wave
Pulse Generator / Injects a rectangular pulse
Signal Generator / Injects waves of selected forms
Step / Injects one rectangular edge
White Noise / Injects random noise
Important Sinks
Graph / Plots output, axes, and permits printingScope / Same as oscilloscope (WYSIWYG)
Kitchen / (Not available in this version)
Important Operators
Discrete
IntegratorTime-limited Integrator
Linear
DerivativeGain
Dot Product
Integrator
Summer
Non-Linear
Function / Place equation in blockLogical Operator / AND, OR, NOR
Product
Quantizer / Quantize the input in given intervals
Limiter Integrator / Integrate over a specified region
Transport Delay / Delay input by a specified amount of time
Switch / Switch between two inputs
Filters
Analog Low Pass / Removes high frequenciesAnalog High Pass / Removes low frequencies
Analog Band Pass / Passes only in the middle (selected)
Analyzers
AveragePSD
Example 1. Modelling viscoelasticity