Education and
Consulting Group
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

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:

plot of sinusoidally-driven damped oscillator

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.

Interfacing with C and Fortran Programs

Matlab has extensive tools for interfacing with existing C and Fortran programs.

Via System Calls from Matlab

Via Dynamically Linked C and Fortran Subroutines

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).

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.

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

Referencing Array Elements

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

Storing and Loading 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.