0% found this document useful (0 votes)
54 views

MATLAB Help From BU

The document provides guidance on learning to use Matlab for engineering solutions. It recommends interactive learning methods like reading the guide, doing tutorials, experimenting with small test data, and using the help command frequently. It also suggests studying well-written code to learn good coding technique and style. The guide covers topics like running Matlab, defining variables, generating arrays, loops, conditionals, solving equations, writing scripts and functions, debugging, and other resources.

Uploaded by

Colin Bunting
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

MATLAB Help From BU

The document provides guidance on learning to use Matlab for engineering solutions. It recommends interactive learning methods like reading the guide, doing tutorials, experimenting with small test data, and using the help command frequently. It also suggests studying well-written code to learn good coding technique and style. The guide covers topics like running Matlab, defining variables, generating arrays, loops, conditionals, solving equations, writing scripts and functions, debugging, and other resources.

Uploaded by

Colin Bunting
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Engineering Solutions with Matlab

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

5 Generating Arrays Automatically 7


5.1 The colon (:) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
5.2 Equally spaced data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

6 Loops 7
6.1 Explicit loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
6.2 Implicit loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

7 Conditionals 7

8 Solving matrix equations 8

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

10 Debugging scripts and functions 13


10.1 Error descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
10.2 Strategies for identifying errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
10.2.1 Halt execution and check variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
10.2.2 Simplify the code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

11 Acknowledgements 14

12 Your feedback 14

13 Links to other Matlab resources 14

1 How do I learn Matlab?


As with any learning experience, there is no single recipe that is optimal for everyone. Each person has a
unique learning style and should blend learning activities to suit that style. Below we summarize learning
activities that have proven most helpful to students learning Matlab:

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

2.2 Specifying file locations


Matlab first searches for files in the current working directory then searches through a list of directories
known as the search path.

2.2.1 Current Working Directory


A current working directory is defined in which Matlab will, unless told otherwise, write files and look first
for files. This directory may be displayed by the pwd2 command and may be changed by the cd3 command.

2.2.2 Search path


After searching the current working directory for a file, Matlab searches directories on a list known as its
search path. This list may be displayed and changed by the path4 command. The following code displays
the path:
path
while the following code adds the directory c:\x\y to it:
path(path,’c:\x\y’)
In cases where two or more files with the same name reside in different directories, the file in the directory
that appears first in the path will be used.

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.1 Getting information on variables in the workspace


The term workspace refers to the collection of variables that have been assigned either interactively or
within scripts that have been executed. The who5 command gives a listing of all existing variables. The
whos6 command gives additional information on sizes and classes of variables. This information is described
more fully in section 4 below.
2 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/pwd.shtml
3 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cd.shtml
4 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/path.shtml
5 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/who.shtml
6 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/who.shtml

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 .

3.3 Recording an interactive session


The diary8 command records commands entered as well as the resulting output. The recording begins by
typing diary filename, where filename is the name of the file where the information is stored. The
recording may be turned off or on or off by typing diary off and diary on.

3.4 Suppressing output


Matlab will automatically print the results of a command to the workspace, which is inconvenient if the
result has more than a few lines. This printing can be suppressed by adding a semicolon (;) at the end of
any command.

3.5 Exiting Matlab


You may quit an interactive session by simply typing quit9 .

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

4.1 Variable Types


When a numeric variable is defined in Matlab, it is automatically classified as a double precision array of
numbers even if that array has one element (a scalar). Matlab supports 15 different variable types which are
described in the Matlab documentation10 . A variable may be converted to a particular type by using the
Matlab command with the same name as the variable type. This is illustrated in the following example by
the use of the single11 command to create a single precision variable y:

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

x 1x1 8 double array


y 1x1 4 single array

Grand total is 2 elements using 12 bytes

4.2 Special Values



Matlab has functions that return special values, such as π and i = j = −1. These are described in the
Matlab documentation12 . It is highly recommended that these function names not be chosen for user-defined
variables or functions.

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

x 1x1 8 double array

Grand total is 1 element using 8 bytes


Scalars may be complex-valued by using the special value i (see 4.2), as in the following example:

>> z = 2.3 + i*3.4

z =

2.3000 + 3.4000i

>> whos
Name Size Bytes Class

z 1x1 16 double array (complex)

Grand total is 1 element using 16 bytes


12 http://www.mathworks.com/access/helpdesk/help/techdoc/matlab prog/ch10 p19.shtml

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]’

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

5 Generating Arrays Automatically


When working with large arrays, the defining statements described in the previous section are inconvenient
and one must seek automatic ways of generating arrays.

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 =

1.0000 1.3000 1.6000 1.9000

5.2 Equally spaced data


In many applications, one wishes to generate evenly spaced data that is specified by the number of points
and the initial and final values. For such ases, the linspace13 command is very convenient as it eliminates the
need to compute the step size. In the following example, the row vector y with 4 points is generated with a
minimum of 1 and a maximum of 2:
>> y = linspace(1,2,4)

y =

1.0000 1.3333 1.6667 2.0000

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.

6.1 Explicit loops


The following syntax was obtained by typing help for:
FOR variable = expr, statement, ..., statement END

6.2 Implicit loops

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:

• < less than

• > greater than

• <= less than or equal to

• >= greater than or equal to


• == equal to

• ∼= 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

8 Solving matrix equations


The solution of many engineering problems requires the solution of a matrix equation of the form

[A] {x} = {b} . (1)

If the matrix [A] is square, this system is solved by premultiplying both sides by the inverse of [A],

{x} = [A]−1 {b} . (2)

The following interactive example illustrates this process:

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

9 Writing scripts and functions


Most serious work in Matlab is not done interactively but through commands stored in files named *.m,
where * stands for any filename. There are two types of files:
15 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/relationaloperators.shtml

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.

9.1 Example script


The following is an example of a relatively simple script that plots a circle:

%
% 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
%

print -deps plot_circle.eps

9.2 Example function


The following is an example of a relatively simple function that computes x and y locations for a circle with
radius R:

%
% compute_circle.m
%
% Sample Matlab function that plots a circle of unity radius.
%
% Written by J. Gregory McDaniel
%

function [x,y] = compute_circle(R, n_theta)

%
% Define evenly spaced angles in radians
%

theta = linspace(0, 2*pi, n_theta);

%
% 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
%

[x,y] = compute_circle(R(iR), n_theta);

%
% 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
%

xlabel(’x location (m)’)


ylabel(’y location (m)’)
title(’Plot of a circle with 1 m radius’)

%
% Print to a file for inclusion in a document
%

print -deps test_compute_circle.eps

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

– separated by an underscore, so that x_y would represent the variable xy .


– separated by the letters Sub, so that xSuby would represent the variable xy .

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.

9.4 Built-in functions


Matlab has many built-in functions. A comprehensive list linked to help on those functions is available online
at [?]

10 Debugging scripts and functions


Even experienced Matlab users encounter errors in their scripts and functions, just as typists make typo-
graphical mistakes. In this section, we survey some common errors and propose strategies for identifying
and fixing them.

10.1 Error descriptions


Whether you are using Matlab interactively or not, Matlab issues an error description and stops execution
whenever it encounters an error. Following is an example of an error that arises during interactive use of
Matlab:

>> clear all


>> y = xˆ2
??? Undefined function or variable ’x’.

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?

10.2 Strategies for identifying errors


10.2.1 Halt execution and check variables
Stop execution with a keyboard command and check variables with a whos command.

10.2.2 Simplify the code


Sometimes, they erroneous line is not the one at which execution is halted. Identifying the erroneous line is
therefore difficult. In many cases, one can comment out suspicious lines and attempt to rerun the code.

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

13 Links to other Matlab resources


• www.mathworks.com
Homepage of The Mathworks, Inc., makers of Matlab
• www.engin.umich.edu/caen/technotes/matlab.pdf
Matlab basics with brief command-oriented examples

• 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

You might also like