Matlab
Quick Reference Guide
University of Waterloo, Ontario, Canada
Contents
[About this Document] [Usage Tips]
[Sample Session]
[Methods of Working] [Data Types]
[Commands to Know]
Back to: Scientific
Computing Software at Waterloo
This document is intended to be a concise description of the "essential"
information that you need to know in order to use Matlab effectively. Matlab
has on-line help for all of its functions, extensive on-line demonstrations
(type "demo" at the Matlab command prompt). This document is intended to bridge the gap
by providing the essentials in a readily accessible format.
Back to Contents.
Tips for Working Effectively with Matlab
>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
Use the who or whos commands to list your assigned
variable names. clear removes assigned variables.
Use save and load to save and retrieve results.
Expressions and values are assigned to names with "=".
Any variables in expressions must have pre-assigned values.
>> a=2; b=3; c=4; x=7; quad = a*x^2 + b*x + c;
Forward single quotes indicate a "string" of characters,
useful for passing m-file names, etc. to functions.
>> cd('n:\matlab\mfiles')
>> cd n:\matlab\mfiles
Variable and function names are case sensitive:
>> Good := sin(pi/4); Bad := Sin(Pi/4);
(The irrational number is pi; Pi has no predetermined meaning.)
- Vectors may be assigned as ranges:
>> x = 0:100; % produces an array containing the integers
0 through 100
>> x = 0:0.1:100; % produces an array from 0 to 100 in increments
of 0.1
- Most Matlab functions operate on matrix and vector arguments in the expected manner.
>> x = 0:3 % --> 1 2 3
>> y = 2*x % --> 2 4 6
>> x + log10(y) % --> 1.3010 2.6021 3.7782
>> x * y % Default is matrix multiplication .... error!
>> x .* y % --> 2 8 18 (Dot before operator forces element-wise operations)
- There are various methods of referencing array elements (see below).
- Variables defined inside functions are local to those functions unless
declared as global both inside the function and at the command
prompt (or in an initialization m-file script).
- Matlab works to double-precision (16 digits) by default. The format
of displayed results is controlled with the format command.
- Matlab has a large set of core functions, based on LINPACK and EISPACK
algorithms. These functions are supplemented by "toolboxes" which
define extra functions for various specific areas of mathematics or engineering.
- To find what functions Matlab has available, type help or
help function_name, or help toolbox_name. Search for
key words in the help files with lookfor.
>> help optim % functions in optimization toolbox
Add help information to your own m-files in a commented section at the
top of the file. Access it by typing help your_function_name
- List file names in the current directory with ls or dir.
View file contents with type. Execute shell programs by preceeding
the command with !.
>> !vi my_mfile.m
- Many of Matlab's functions are written in the Matlab language. A good
way to learn about how to write your own functions is to look at how Matlab's
own functions are written. On most Unix systems these are located in /software/matlab/distribution/toolbox,
and on Watstar in j:\ml\toolbox.
- Some Matlab functions are compiled (C) programs for faster exection.
The Compiler Toolbox lets you complile your own m-files too.
- Although Matlab is an interpreted language, effective use of its vector/matrix
functions make its computations execute as fast as compiled C programs.
For help in "vectorizing" your m-files see the technical document
provided by the Mathworks.
- Matlab can call existing C and Fortran programs and can be called by
them as a computation "engine". See below.
Back to Contents.
Sample Session
Create an m-file called spr_damp.m (or for version 4 users, spr_damp_v4.m) defining a spring-damper system (using any text editor):
% Definition of Spring-Damper system
% M*x'' + D*x' + K*x = f(t) or x'' + (D/M)*x' + (K/M)*x = f(t)/M
% or expressed as a system of first-order ODEs:
% x1' = x2
% x2' = (1/M)*f(t) - D*x2 - K*x1
% where f(t) is defined by a function named in a string variable, FORCEFUN
function xdot = spr_damp(t,x)
global M D K FORCEFUN
xdot(1,:) = x(2);
xdot(2,:) = (1/M)*( feval(FORCEFUN,t) - D*x(2) - K*x(1) );
Create a file called delaysin.m defining the forcing function
for the system (using any text editor):
% Sinusoidal forcing function for spring-mass-damper problem, smd_prob.m
function f = delaysin(t)
global FIRSTCALL AMPLITUDE DELAY
if FIRSTCALL == 0,
AMPLITUDE = input('Amplitude of forcing sine wave: ')
DELAY = input('Delay time: ')
FIRSTCALL=1;
end;
if t >= DELAY,
f = AMPLITUDE*sin(t-DELAY);
else
f = 0;
end;
Create a script file, smd_prob.m (or for version 4 users, smd_prob_v4.m) to solve/explore this ODE system and plot the results:
global M D K FORCEFUN FIRSTCALL AMPLITUDE DELAY
% initialize Mass (M), Damping Coeff. (D), and Spring Constant (K):
M=2, D=1.656, K=40
% Set the flag which indicates where the forcing funtion has been called:
FIRSTCALL=0;
% Define the forcing function by asking user for the name of an m-file
% or built-in function such as "sin" (this use of "input" takes a string value):
FORCEFUN = input('Type the name of the forcing function: ','s')
% Set starting time and finishing time:
t0=0, tf=10
% Specify initial conditions:
x0=[1;0] % note: x0(1)=x(t=0), x0(2)=dx/dt(t=0)
% Solve the system of first-order ODEs
[t,x]=ode45('spr_damp',[t0,tf],x0)
% Plot the results:
hold on % keep adding additional plots to plot window
plot(t,x(:,1)); % where x(:,1) is the first column of x, x(t)
% plot zero displacement axis
plot(t,zeros(size(x(:,1))),'w-');
% add titles
title('Forced, Damped Oscillator');
xlabel('Time in seconds');
ylabel('Displacement');
hold off
Start Matlab and enter the following (assuming the m-files are in directory
n:\matlab):
>> cd 'n:\matlab'
>> smd_prob %run the script file smd_prob.m
Type the name of the forcing function: delaysin
Amplitude of forcing sine wave: 100
Delay time: 0
With the following plot as output:

Back to Contents.
Methods of Working With Matlab
Interactive Use
Matlab is often used interactively, i.e. commands are typed in directly
at the command prompt. This is also the method of developing script and
function m-files.
Scripts and Procedures
Matlab is also an interpreted programming language.
- Text files containing Matlab commands are executed as they are read
in, by using the name of an m-file at the command prompt.
- Under Unix, Matlab may be used directly as a processor, taking input
from a file and printing output to a file.
- Matlab language may be used to write your own functions and procedures
which take arguments and return results. These must be defined in m-files,
not at the command prompt.
- Your own function m-files are called by using their names with valid
arguments. The name of a function m-file must be the same as the name of
the function.
Interfacing with C and
Fortran Programs
Matlab has extensive tools for interfacing with existing C and Fortran
programs.
Via System Calls from Matlab
- As a "quick-and-dirty" approach
- use the unix command to run
a compiled program under Unix and return it's results to Matlab.
- use the ! (bang) to execute what follows as a system
command then return control to Matlab e.g. run a Fortran program which
reads a data file produced by Matlab then writes a data file to disk.
- This method may not be efficient due to disk activity and
additional overhead required by running the external program separately from Matlab.
Via Dynamically Linked C and Fortran Subroutines
- Matlab can call existing C and Fortran programs as MEX files (Matlab
EXternal) just as it can call interpreted m-files.
- You must add a "gateway" section to your existing C or Fortran code
using routines from the External Interface Libraries (see the External
Interface Guide)
- Recompile your modified C(++) or Fortran source code into MEX files
(runable only from within Matlab) using the "fmex" and "cmex" shell scripts
- Matlab uses a MEX file in preference over an m-file of the same name in the same directory.
- Note: Many NAG subroutines have already been ported to Matlab as MEX files,
as the NAG Toolbox (available on Unix).
Calling Matlab as a Computation Engine from C and Fortran Programs
C and Fortran programs can call Matlab as a computation "engine"
(but not Matlab's graphical functions).
- Quick-and-dirty way: From C only, use system calls to run a Matlab
script file and save results to a file, then read the data from your C
program.
- Use Matlab interface subroutines from the Matlab Engine Libraries
execute Matlab commands directly.
- Read and write Matlab data files (MAT-files) using routines from
the MAT-file Libraries.
Matlab's C Compiler Toolbox (available at UW on Unix only)
You can compile your m-files as C-MEX for faster execution.
Significant speed increases are obtained for m-files containing
"while" and "for" loops, but such loops can also
be "vectorized" (converted to vector/matrix manipulations)
which also achieves similar speed increases.
- Type help mcc in Matlab for complier options. The
-i and -r options can significantly speed up the
compiled code.
- You can only compile "function" not "script" m-files.
- Sparse matrices are not supported by the compiler toolbox.
- Create stand-alone C programs via the Compiler Toolbox and the
C Math Library (can't use interactive input, Matlab graphics, file I/O
functions, or Simulink functions).
Back to Contents.
Data Types
The two-dimensional, complex-valued matrix (array) is the basic
internal data type in Matlab.
All other structures are sub-types.
External data is in the form of ASCII text files (script and function m-files), and binary data files (.mat files) for stored data.
Arrays, Matrices, Vectors, Strings
- Vectors are just arrays with a single row or column.
- Scalars are just single element arrays.
- Strings are row vectors with one character in each column.
- Matrices may contain strings, e.g. % guys = ['Dave';' Tom'],
as long as all columns have the same number of string characters.
- The indices of rows and columns are integer values beginning at one.
The following examples indicate the syntax for defining matrices in
Matlab, referencing, and manipulating elements:
- >> A = [1,2,3;4,5,6;7,8,9] % create a 3 by 3 matrix
- >> B = [10 11;12 13] % create a 2 by 2 matrix (alternate
syntax)
- >> A(2,1) % access the element of A in row 2, column 1 (i.e.
4)
- >> C = A(1,1:3) % extract the first row, columns 1 to 3,
of A
- >> C = A(1,:) % extract first row, all columns of A
- >> D = A(:,[1,3]) % extract first and third columns of A
- >> A([1,3],[1,3]) = B % replace elements A(1,1), A(1,3),
A(3,1), A(3,3) with B(1,1), etc.
- >> A([1:2:3],[1:2:3]) = B % replace every second element
in A with elements of B
- >> M = [A,D] % append A and D horizontally
- >> N = [A;C] % stack A and C vertically
Script and Function M-Files
- As mentioned above, m-files are text files containing Matlab commands
which may be accessed from the Matlab command prompt.
- Scripts are just sequences of Matlab commands, executed just as if
they were typed in at the command line.
- Functions are special scripts which take arguments and return results,
and whose internal varialbles are local to the function by default.
Storing and Loading Data Files
- Matlab stores defined variables using the save command
in either binary orASCII text format. These files can be be read with the
load command. Use the functions fscanf and
fprintf to read and write formatted data files.
Back to Contents.
Commands to Know
[who][cd][path]
[clear][global] [print]
[hold][more]
who
- Description:
- Determine what variables are assigned in the work space.
- Usage:
- who
- See Also:
- whos (for more detailed information)
Back to Commands to Know.
cd
- Description:
- Change current directory Matlab is looking in (first) for files and
commands.
- Usage:
- cd n:\matlab\m-files,
cd('n:\matlab\m-files')(Example for DOS; Note that the argument
in second form is a string.)
- See Also:
- path (to add other directories to Matlab's search path)
- pwd (to check the "present working directory")
Back to Commands to Know.
path
- Description:
- Displays/modifies the search path used by matlab when looking for functions.
- Usage:
- path('new_path',path) % prepends a string containing a new path
to the current path
- path(path,'new_path') % appends a new path to the current path
- path % displays the current path
- Example:
- >> path('$HOME/matlab/my_mfiles',path)
See Also:
- blah
Back to Commands to Know.
clear
- Description:
- Removes defined variables
- Usage:
- clear; % clears all defined variables from memory
- clear xxx; % clears just the variable "xxx"
Back to Commands to Know.
global
- Description:
- Sets specified variables to be globally accessible by functions, to
avoid having to pass such variables as arguments.
- Usage:
- global X Y Z % declares X, Y, Z global
- N.B.:
- Global variables must be declared in both the workspace and
in any functions which need to access them. It is a good idea to use capital
letters or other consistent naming scheme to identify global variables
to ease debugging.
Back to Commands to Know.
print
- Description:
- Produces printable output files of various types for the active graphics
window.
- Usage:
- print -deps plot.eps
- % produces an encapsulated PostScript file named plot.eps from
the current plot window
- print -deps -f2 plot2.eps % produces an EPS file from figure window
2
- print -deps -sthermo thermo.eps
- % produces an EPS file from a Simulink block diagram in the window
titled "thermo"
- N.B.:
-
If you plan to bring a figure into a report as an EPS file, it is a good idea
to size the figure within Matlab, before saving it. This will keep the text
labels legible, which might not be the case if you have to resize the figure in
your document. For information on how to do this see these
instructions.
- See Also:
- figure, get, set (for dealing with figure windows and their
properties)
Back to Commands to Know.
hold
- Description:
- Keeps the current figure Window "open" to allow several plots
on the same set of axes.
- Usage:
- hold on % turns keeps current window open
- hold off % turns off; next plot will be in a new window
- See Also:
- plot, plot3, subplot, title, xlabel, ylabel, zlabel, text, legend
Back to Commands to Know.
more
- Description:
- Toggle on and off paging of Matlab output.
- Usage:
- more on; more off
Back to Commands to Know.
Back to Contents.