MATLAB Help From BU
MATLAB Help From BU
J. Gregory McDaniel
Aerospace and Mechanical Engineering Department
Boston University
Boston, Massachusetts 02215
Email: [email protected]
Phone: 617-353-4847
September 11, 2003
Contents
1 How do I learn Matlab? 2
2 Running Matlab 3
2.1 Starting Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Specifying file locations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2.1 Current Working Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2.2 Search path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3 Interactive use 3
3.1 Getting information on variables in the workspace . . . . . . . . . . . . . . . . . . . . . . . . 4
3.2 Automatic completions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.3 Recording an interactive session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.4 Suppressing output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.5 Exiting Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4 Defining Variables 4
4.1 Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.2 Special Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4.3 Scalars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4.4 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.5 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
6 Loops 7
6.1 Explicit loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
6.2 Implicit loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
7 Conditionals 7
1
9 Writing scripts and functions 9
9.1 Example script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
9.2 Example function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
9.3 Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
9.4 Built-in functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
11 Acknowledgements 14
12 Your feedback 14
• Read this guide. The structure and content of this guide have been chosen based on the author’s
experiences teaching Matlab to engineering students for the past ten years in a variety of classes and
contexts.
• At the Matlab prompt, type help demo and proceed through the tutorial provided by The Mathworks.
• Play. This is perhaps the most efficient yet undervalued means of learning new commands and features.
Using Matlab interactively, generating small test data, and experimenting with new commands builds
confidence and can even be fun.
• Use the help command a lot. This command is invoked by typing help command, where command
is the name of the command that you are learning. Even though you may feel confident about a
particular command, new versions of Matlab are continually produced and commands often provide
new functionalities. Use the help command when debugging a script that fails at a function call.
Copying and editing a sample call to a function from the results of the help command is a particularly
effective way to learn a new command.
• Study well-written code and become a connoisseur of good technique and style. Matlab is an open
source software, so any built-in Matlab function is available for viewing by finding the *.m file on your
computer. In addition, The Mathworks maintains an online collection1 of user-contributed code.
In addition to these activities, it is strongly advised that the student have a purpose or problem in
mind when learning Matlab. Attempting to learn the entire Matlab suite of commands in a vacuum or out
of context is a recipe for frustration. Start with simple commands and build up in complexity. When a
particular sequence of commands produces an undesired result, take a step backwards in complexity until
the result is fully understood and then step forward.
1 http://www.mathworks.com/matlabcentral/
2
2 Running Matlab
2.1 Starting Matlab
On most platforms, Matlab is started by clicking the Matlab icon or typing matlab at a command prompt
of the operating system. Depending on the version and setup of Matlab, the following windows might open:
Command Window This is the interactive window in which you may execute commands, such as running
scripts and functions. Many examples in this guide will be executed from this window.
Command History List of command previously typed in the command window.
Current Directory Display of files in current directory
Workspace Graphical display of variables in the workspace.
Launch Pad User interface to programs, help, and demos for Matlab and its toolboxes.
3 Interactive use
Most first-time users of Matlab begin by using the software interactively. Moving to the command window
allows the user to enter native Matlab commands and to execute user-written functions and scripts. The
symbol >> is the command prompt that indicates Matlab is awaiting commands from the user.
3
3.2 Automatic completions
In order to reduce the amount of typing in the command window, two ways of automatically completing
commands are provided. Pressing the up arrow recalls previously typed commands in reverse order, so that
the most recent command appears first. Typing the first letter(s) of a command and then the up arrow
limits the recalled commands to those having the typed letters in the beginning of their names. Typing the
first letter(s) and then the tab key produces a list of all functions, variables, files, structures, or properties
beginning with those letters. Documentation on up arrow and tab completion may be found in the Matlab
documentation7 .
4 Defining Variables
Every variable in Matlab represents an array, which is defined by the McGraw-Hill Dictionary of Scientific
and Technical Terms as
“A collection of data items with each identified by a subscript or key and arranged in such a way
that a computer can examine the collection and retrieve data from these items associated with a
particular subscript or key.”
>> x = 0.1
x =
0.1000
>> y = single(0.1)
7 http://www.mathworks.com/company/digest/july03/tabcomp.shtml
8 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/diary.shtml
9 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/quit.shtml
10 http://www.mathworks.com/access/helpdesk/help/techdoc/matlab prog/ch10 p20.shtml
11 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/single.shtml
4
y =
0.1000
>> whos
Name Size Bytes Class
4.3 Scalars
Scalar variables are defined by assigned a single number, either real- or complex-valued, to a variable. In
the following example, the value 1.2 is assigned to x:
>> x = 1.2
x =
1.2000
>> whos
Name Size Bytes Class
z =
2.3000 + 3.4000i
>> whos
Name Size Bytes Class
5
4.4 Vectors
A vector is a list of numbers. A row vector contains one row and many columns. A row vector is defined by
separating elements with spaces or commas and surrounding them by brackets, as in the following example:
>> x = [1, 3, 8]
x =
1 3 8
A column vector is defined by separating elements with semicolons and surrounding them by brackets,
as in the following example:
>> y = [2; 5; 7]
y =
2
5
7
A column vector can be made into a row vector, and vice-versa, by taking a transpose. For real-valued
vectors, this is done by placing an apostrophe (’) after the vector, as in the following example:
y =
2
5
7
which gives the same vector for y as in the previous example.
4.5 Matrices
A matrix is a rectangular or two-dimensional array of elements. Technically, a vector is a special case of a
matrix in which one of the dimensions is unity. The size of a matrix is typically expressed as M × N , where
M is the number of rows and N is the number of columns.
Each row in a matrix is defined as a collection of elements separated by a space or comma. Rows are
separated by semicolons and the entire collection of elements is surrounded by brackets. The following
example defines a 2 × 2 matrix:
>> a = [1, 3; 2, 4]
a =
1 3
2 4
6
5.1 The colon (:)
With the exception of the semicolon, the colon is perhaps the most powerful character in all of Matlab. The
colon should be generally interpreted as a step, and is therefore useful in generating long lists of data. The
command a:b:c generates a row vector that starts at a and proceeds in steps of b coming as close as possible
to c without exceeding it. If b is omitted, as in a:c, then be is assumed to be unity. Therefore, a:c and
a:1:c are equivalent. The following example uses the colon to step from 1 to 2 in steps of 0.3. Note that
the maximum value is not 2:
>> x = 1:0.3:2
x =
y =
6 Loops
Matlab provides two ways of looping through a collection of statements. The explicit loop resembles the
loops found in traditional programming languages by defining a loop variable that increments each time
around the loop. Like many programming languages, Matlab provides a method for looping over a collection
of statements.
7 Conditionals
A conditional is a statement that is executed if a condition is true and is generally implemented by the
if14 command. The following syntax was obtained by typing help if:
IF expression
statements
ELSEIF expression
statements
ELSE
13 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/linspace.shtml
14 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/if.shtml
7
statements
END
The expression represents a question and the statements are executed if the answer is yes. The expressions
typically contain relational operators15 that define the question. These relational operators as follows:
• ∼= not equal to
The order of symbols in the last four items above can be remembered by the order of the english: in “less
than or equal to,” the less symbol appears before equal symbol.
The question in english is formed by placing the word is before the mathematics. For example, the
expression x > y asks “is x is greater than y?”. As an example, the following conditional takes the absolute
value of a variable x:
if(x < 0)
x = -x
end
If the matrix [A] is square, this system is solved by premultiplying both sides by the inverse of [A],
>> A = [1 2 3; 3 2 1; 2 1 3];
>> b = [1; 2; 3];
>> x = inv(A)*b
x =
1.0833
-0.9167
0.5833
8
scripts Each line of a script contains a Matlab command. The script is executed by placing it in the working
directory or search path and typing the script name with its extension.
functions A function must be called, either from a script, another function, or the command prompt. It
accepts input arguments and returns output arguments.
Typically, scripts call functions.
%
% plot_circle
%
% Sample Matlab script that plots a circle of unity radius.
%
% Written by J. Gregory McDaniel
%
%
% Clear the workspace and close figures
%
clear all
close all
%
% Define radius
%
R = 1; % meters
%
% Define evenly spaced angles in radians
%
n_theta = 100;
theta = linspace(0, 2*pi, n_theta); % radians
%
% Compute x and y locations
%
x = R*cos(theta); % meters
y = R*sin(theta); % meters
%
% Plot the circle
%
plot(x, y, ’k-’)
xlabel(’x location (m)’)
ylabel(’y location (m)’)
title(’Plot of a circle with 1 m radius’)
9
%
% Make the axes equal so that the circle is not displayed as an
% ellipse
%
axis equal
%
% Print to a file for inclusion in a document
%
%
% compute_circle.m
%
% Sample Matlab function that plots a circle of unity radius.
%
% Written by J. Gregory McDaniel
%
%
% Define evenly spaced angles in radians
%
%
% Compute x and y locations
%
x = R*cos(theta);
y = R*sin(theta);
The following function calls compute circle a number of times to test its accuracy:
%
% test_compute_circle.m
%
% Tests the function compute_circle.m by plotting three
% circles with different radii
%
% Written by J. Gregory McDaniel
%
10
% Clear the workspace and close figures
%
clear all
close all
%
% Define radii
%
R = [1 2 3]; % meters
%
% Define evenly spaced angles in radians
%
n_theta = 100;
%
% Loop over radii
%
for iR = 1:length(R)
%
% Compute the x and y locations by calling the function
% compute_circle
%
%
% Plot the circle
%
plot(x, y, ’k-’)
%
% Hold the plot so that the next plot command does not clear
% the plot
%
hold on
%
% Make the axes equal so that the circle is not displayed as
% an ellipse
%
axis equal
end
11
%
% Add labels
%
%
% Print to a file for inclusion in a document
%
9.3 Style
The stylistic choices you make when writing scripts and functions greatly affect the probability that others
will understand, use, and modify your work. Properly written scripts and functions do more than calculate
or plot correctly; they also communicate what has been done. Matlab allows for a wide variety of pro-
gramming styles, however many people have begun to adopt stylistic conventions that provide consistency
among functions and scripts. This consistency reduces programming errors and allows your code to be more
easily read and interpreted by others. Perhaps the best guide to current convention is an article entitled
MATLAB Programming Style Guidelines16 . It is highly recommended that students follow the guidelines
detailed in that article.
There are additional stylistic choices that enhance the clarity of code written to solve engineering prob-
lems. These are listed below:
• Whenever possible, match variable names to those used in any existing documentation on the problem
you are solving. The existing documentation may include textbooks, articles, or notes. Some docu-
mentation almost always exists prior to writing a script and if it does not, consider writing it first. Cite
that documentation in the comment lines of your code. This makes your code “self-documenting,” in
that the reader can directly match variables and equations in the code to the documentation. At the
least, this allows for easy checking of code against equations in the documentation. Greek variables
may be matched by writing out the greek letter, such as alpha for the greek letter α.
• Subscripts on variables in the documentation should be included at the end of the variable name and
should either be
The latter option is preferable if the variable name will appear in text associated with plots.
• Include your name in the comment block of every code that you write. This will insure that you receive
credit if your code is used by others.
• Never include absolute pathnames containing a directory structure in your code. If, for example, your
code executes a script called script.m in the directory c:\x\y, then add c:\x\y to your search path,
as described in section 2.2. Do not put the path in your code. Following this guideline will make your
code more portable, as another user might not have the same directory structure as you. They might
not even be using the same platform.
• If a function is only invoked a few times and is not a commonly used function, copy the sample
command statement from the help and paste it in your code. Prior to calling the function, define the
16 http://www.datatool.com/MatlabStyle.pdf
12
input variables used in the call statement. In this way, your variable names will match those of the
documentation and make it easier to check the arguments.
In this example, the error was due to the fact that Matlab was asked to calculate y without knowing x. In
the following example, an error is generated because the product of xy is only defined when the number of
columns in x matches the number of rows in y:
>> x = [1 2 3];
>> y = [4 5 6];
>> x*y
??? Error using ==> * Inner matrix dimensions must agree.
In the above two examples, the errors are rather obvious and easily identified by Matlab’s error descrip-
tions. In the following example, the error is less obvious:
>> x = [1 2 3];
>> y = [4 5 6];
>> z = [7 8 9];
>> x*y*z
??? Error using ==> * Inner matrix dimensions must agree.
Which inner dimensions disagree? Is it x and y or y and z?
13
11 Acknowledgements
The author is grateful to the College of Engineering at Boston University for supporting the writing of this
guide. Professor Eisenberg was an immediate and long-lasting supporter of this effort. The author would
also like to thank the following people for providing suggestions and course materials that supported the
writing: Professors Stormy Attaway, Solomon Eisenberg, James Sullivan, Morton Isaacson, Sheryl Grace,
William Oliver, Thomas Szabo, Maja Bystrom, Irving Bigio, Mark Horenstein, Tanya Roziner, Ronald Roy,
Michael Ruane, Selim Unlu, R. Glynn Holt, James Collins, Allan Pierce
The author is also especially grateful to the students who, over the past decade, shared their Matlab
experiences, secrets, and codes.
12 Your feedback
Your feedback will help to improve this guide. Please comments and suggestions to the author at [email protected].
• www.spicerack.sr.unh.edu/ mathadm/tutorial/software/matlab
• www.math.ufl.edu/help/matlab-tutorial
• www.math.siu.edu/matlab/tutorials.html
• www.indiana.edu/ statmath/math/matlab/gettingstarted
• www.tutorgig.com/searchtgig.jsp?query=Matlab
14