The Basics of Matlab: Jeffrey O. Bauer
The Basics of Matlab: Jeffrey O. Bauer
MATLAB
Jeffrey O. Bauer
Contents
-i-
MATLAB Programming Basics ...................................39
Script Files.............................................................................................39
m-files...............................................................................................39
Side Effects.......................................................................................41
Comments.........................................................................................42
Function Files .......................................................................................42
Syntax...............................................................................................42
Input and Output Arguments.............................................................43
Primary and Secondary Functions.....................................................44
Input and Output .................................................................................46
User Input .........................................................................................46
Text Output.......................................................................................46
Flow Control .........................................................................................50
Relational and Logical Operators......................................................50
Operator Precedence .........................................................................52
if … else … Statements..............................................................53
switch Statements ........................................................................54
for Loops........................................................................................55
while Loops ...................................................................................56
break..............................................................................................57
return............................................................................................58
Vectorization ........................................................................................58
Vectors vs. Loops .............................................................................58
Copying ............................................................................................58
Pre-allocating Memory .....................................................................60
Four Elegant Devices ........................................................................60
Variable Input and Output.................................................................60
Global Variables ...............................................................................60
feval..................................................................................................61
Inline Functions ................................................................................61
- ii -
Numerical Problem Solving Basics ...........................63
Problem Solving Methodology......................................................63
Report of Solution.............................................................................63
Work.................................................................................................63
Stepwise Refinement ..............................................................63
Organizing and Documenting ........................................................64
Prologue ...........................................................................................64
Visual Blocking ................................................................................65
Meaningful Variable Names .............................................................66
Comments.........................................................................................66
Robust Programming.........................................................................67
Problem Examples..............................................................................67
Nonlinear Equation ...........................................................................68
Linear System ...................................................................................72
Curve Fitting.....................................................................................76
Numerical Integration .......................................................................81
References ......................................................................................................85
- iii -
MATLAB Basics
MATLAB is a high-level technical computing language and interactive environment for
algorithm development, data visualization, data analysis, and numerical computation. Using
MATLAB, you can solve technical computing problems faster than with traditional
programming languages, such as C, C++, and Fortran.
MATLAB contains mathematical, statistical, and engineering functions to support all common
engineering and science operations. These functions, developed by experts in mathematics, are
the foundation of the MATLAB language. The core math functions use the LAPACK and BLAS
linear algebra subroutine libraries and the FFTW Discrete Fourier Transform library.
All the graphics features that are required to visualize engineering and scientific data are
available in MATLAB. These include 2-D and 3-D plotting functions, 3-D volume visualization
functions, tools for interactively creating plots, and the ability to export results to all popular
graphics formats. You can customize plots by adding multiple axes; changing line colors and
markers; adding annotation, LaTEX equations, and legends; and drawing shapes.
MATLAB provides a high-level language and development tools that let you quickly develop
and analyze your algorithms and applications. The MATLAB language supports the vector and
matrix operations that are fundamental to engineering and scientific problems. It enables fast
development and execution. With the MATLAB language, you can program and develop
algorithms faster than with traditional languages because you do not need to perform low-level
administrative tasks, such as declaring variables, specifying data types, and allocating memory.
In many cases, MATLAB eliminates the need for ‘for’ loops. As a result, one line of MATLAB
code can often replace several lines of C or C++ code. At the same time, MATLAB provides all
the features of a traditional programming language, including arithmetic operators, flow control,
data structures, data types, object-oriented programming (OOP), and debugging features.
This document corresponds to MATLAB 2006R+ and the toolboxes added to it for Wayne State
College, Nebraska.
Typographical Conventions
Throughout this guide commands will be presented in mono-spaced font, i.e. >> help.
Running MATLAB
Starting MATLAB
To invoke MATLAB open a terminal and type the shell command `matlab'. A MATLAB
splash screen appears and a few seconds later MATLAB will open. The cursor should be setting
behind the prompt “>>” in the command window. MATLAB is command driven for the most
part. Menus are used mostly to manage files and the display.
-1-
The easiest way to learn how to use MATLAB is by doing. So, start playing. It is recommended
that you try all the examples in this guide.
If you get into trouble, you can usually interrupt a MATLAB process by typing Control-C
(usually written C-c for short). C-c gets its name from the fact that you type it by holding down
CTRL and then pressing c. You will normally return the MATLAB prompt.
To exit MATLAB, type quit or exit at the prompt. You can also exit by clicking on the X in the
upper right corner. (MATLAB functions like Windows-based programs.)
A great deal of work can be accomplished in the MATLAB command environment. However,
there are other screens that can be accessed that can help productivity.
Evaluating Expressions
Expressions are evaluated by entering them after the >> followed by a carriage return. MATLAB
displays the values preceded by “ans =”.
MATLAB follows the algebraic order of operations. Unary operators have right associativity and
binary operators have left associativity.
Unary Operators
+ (positive)
- (negative)
Binary Operators
+ (addition)
- (subtraction)
* (multiplication) (Multiplication is not inferred.)
/ (left-hand division)
\ (right-hand division)
^ (exponent)
( ) (only grouping symbols allowed.)
>> 2 + 5 – 3
ans =
4
>> ans – 3
ans =
1
>> a = 12, b = 5
a =
12
-2-
b =
5
c =
13
>> 2/3
ans =
0.6667
>> 2\3
ans =
1.5000
>> pi
ans =
3.1416
>> sin(pi/3)
ans =
0.8660
>> log(10)
ans =
2.3026
Variables
MATLAB allows you to assign variables to numeric and/or string values. This is accomplished
using the equals sign, “=”. There were a few examples of variable assignments in the previous
section.
>> variable_name = 13
variable_name =
13
-3-
>> array_name = [2 3 4 5]
array_name =
2 3 4 5
string_name =
string
You can suppress output to the screen by ending an instruction or assignment with a “;”.
The name of a variable can contain up to 31 characters. The name must start with a letter. The
remaining 30 characters can be letters, numbers, or the underscore, “_”. Variable names are case
sensitive, e.g. x and X are not the same.
Variable names should be descriptive but not so long they are unwieldy.
Be careful not to use the name of a built-in constant or function to name your variables.
MATLAB doesn’t stop you from doing so. A strategy to determine if a name is already being
used is to 1) type help var_name_of_your_choice and read the response, and 2) type
var_name_of_your_choice and see if the name has been assigned.
-4-
acos(expression)
atan(expression)
atan2(y, x) (inverse tangent that is quadrant specific for the supplied
y- and x- coordinates)
exp(expression) (exponential function with base e = 2.718... )
log(expression) (logarithmic function with base e = 2.718... )
log10(expression) (logarithmic function with base 10)
log2(expression) (logarithmic function with base 2)
Functions and commands are semantically different. Functions usually have input and output
arguments. For example
>> y = sin(pi/3)
uses the sin function with the input argument of pi/3 and assigns the value of its output
argument to y. The input arguments of functions are surrounded by parentheses.
A command such has help can have an input argument. But, the argument is not surrounded by
parentheses. The command clear needs no arguments. Most commands stream output to the
command window or perform some control function.
The truth be told, commands are functions, however most functions are not commands. This
means that a command can be invoked with a parenthesized argument. Functions cannot be
invoked with un-parenthesized arguments, i.e. log 10 will produce a meaningless result.
The format command allows you to control the manner in which numeric values are displayed.
The command does not affect the manner in which computations are performed. The default is
short. Some of the choices are:
-5-
format short (Scaled fixed point format with 5 digits.)
format long (Scaled fixed point format with 15 digits for double and 7 digits for
single.)
format short e (Floating point format with 5 digits.)
format long e (Floating point format with 15 digits for double and 7 digits for
single.)
format short g (Best of fixed or floating point format with 5 digits.)
format long g (Best of fixed or floating point format with 15 digits for double and
7 digits for single.)
DIARY
The diary command is used to open a pre-existing diary or to open a new one. Any text
displayed prior to opening the diary is not recorded to the diary. If a diary already exists when
opened, all text will be written to the end of the existing file.
or
>> diary('mydiary.txt')
A diary is closed with the diary off command or it is closed automatically when exiting
MATLAB.
A saved diary can be opened and edited with any text editor or word processor.
WORKSPACE
The workspace consists of all the variables and their values that are used during a work session.
It can be saved to a data file with a .mat suffix. The command save is used.
The file will be saved to the present working directory (pwd). You can save to a different
directory by changing to the directory before issuing the save command, or by providing a
-6-
complete path name for the file. If you are saving to a subdirectory of the pwd, the name of the
subdirectory must be included with the file name.
or
To save graphs or script files created with an editor it is easiest to use the save choice on the file
menu.
You can load external data using the load command. The data must be stored as a .mat file in
the MATLAB path.
If the data is not stored in the MATLAB path, then a complete path name must be used, similar
to what was done with save.
>> load /home/username/matlab/my_variables
MATLAB's Workspace
MATLAB's workspace is a graphical screen that is used to manage variables during a work
session. A variable can be removed from memory by executing the command clear
variable_name. clear used without a variable name will purge the entire memory.
Functions as well as variables can be cleared.
The MATLAB workspace can also be managed graphically. Once in the workspace screen, a
new variable can be added or an existing one, edited. Using the array editor is the most efficient
way of entering very large matrices. For a 10x10 matrix that contains mostly zeros, execute the
instruction
-7-
>> a=zeros(10)
a =
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
Now switch to the workspace and double click on the variable a (or select a and choose the
edit option). A spreadsheet like screen will open. You can then select the appropriate cells and
change their entries.
The workspace also has a graphing feature. Different arrays can be selected and a host of
different plots can be displayed without using the command screen.
If the workspace is not already opened, the command workspace will open it.
MATLAB has two versions of help. Typing help in the command window will display a text
list of the available functions and scripts. help function_name will display a synopsis of a
function or script.
-8-
The command lookfor keyword will search for functions or scripts that use the word in
their description.
The command helpwin works the same as help, but will display the information in a web
browser that can be navigated by topic or index.
MATLAB Preferences
MATLAB can be configured for personal preferences. The preferences menu is under the File
menu. Screen layout can be configured with the Desktop menu. The final layout can then be
saved. To reduce start up time you should close unused screens, especially the helpwin screen.
Before exiting MATLAB you should close all screens except the command window.
-9-
Editing What You Have Typed
At the MATLAB prompt, you can recall, edit, and reissue previous instructions using Emacs- or
vi-style editing instructions. The default keybindings use Emacs-style instructions. For example,
to recall the previous instruction, type Control-p (usually written C-p for short). C-p gets its
name from the fact that you type it by holding down CTRL and then pressing p. Doing this will
normally bring back the previous line of input. C-n will bring up the next line of input, C-b will
move the cursor backward on the line, C-f will move the cursor forward on the line, etc.
You can also use the up- and down-arrow to navigate through previously issued instructions. If
you retype or reissue an instruction, all the instructions that followed its initial issuance may also
need to be reissued in their chronological order.
>> a = [1, 2, 3, 4]
MATLAB will respond by printing the array in a neatly spaced row. MATLAB can also create
column vectors, for example
>> b = [1, 2, 3, 4]'
b =
1
2
3
4
The " ' " is a transpose instruction that in this case converts a row vector into a column
vector. Sequences can be produced as follows
>> c = 1:100;
Ending an instruction with a semicolon prevents MATLAB from printing to the screen. The
result of the above instruction would be the sequence 1, 2, 3, ..., 100 stored as an
array.
>> d = 1:5:100;
The 5 in the example above serves as a step size. The result is the sequence 1, 6, 11, ...,
96 stored as array d. If the step size is omitted (as in the first example) it is taken to be 1.
- 10 -
You can also count backwards.
>> e = 100:-2:0
To create an array with equally spaced elements between two values do the following.
f =
2.0000 2.3333 2.6667 3.0000 3.3333 3.6667 4.0000 4.3333
4.6667 5.0000
The last number (10 in the previous example) is the number of desired elements in the array.
>> f(5)
ans =
3.3333
A sub-array can be formed from a larger array by using the sequence notation introduced earlier.
sub_f =
2.3333 2.6667 3.0000 3.3333 3.6667
Array Arithmetic
MATLAB has a convenient operator notation for performing array arithmetic. A “.” is placed in
front of the arithmetic operators (already described). Arrays must be the same length.
6 20 42 88 130 204
- 11 -
>> a./b
ans =
>> a.\b
ans =
1.5000 1.2500 1.1667 1.3750 1.3000 1.4167
>> a.^2
ans =
4 16 36 64 100 144
Most array operations are performed element by element. Functions can also be applied to
elements of an array.
>> sqrt(b)
ans =
>> cos(b)
ans =
>> sum(a)
ans =
42
>> length(a)
ans =
- 12 -
>> norm(a)
ans =
19.0788
-5 16 9
>> dot(u,v)
ans =
38
Deleting an Element
>> f(3)=[]
f =
2.0000 2.3333 3.0000 3.3333 3.6667 4.0000 4.3333 4.6667
5.0000
>> f(2:4)=[]
f =
2.0000 3.6667 4.0000 4.3333 4.6667 5.0000
Creating a Matrix
To create a new matrix and store it in a variable so that it you can refer to it later, type the
instruction
MATLAB will respond by printing the matrix in neatly aligned columns. Remember ending an
instruction with a semicolon will prevent the result from being printed to the command window.
will create a 3 row, 2 column matrix with each element set to a random value between zero and
one. You can check in the workspace to see that a matrix was created.
- 13 -
To display the value of any variable, simply type the name of the variable. For example, to
display the value stored in the matrix b, type the instruction
>> b
b =
0.9501 0.4860
0.2311 0.8913
0.6068 0.7621
The elements of a matrix are identified with subscripts (indices) inside of parentheses, e.g.
>> b(3,2)
ans =
0.7621
Subscripts must be natural numbers, i.e. 1, 2, 3, 4, … The first index identifies the row and the
second index identifies the column.
A sub-matrix can be formed from a larger matrix in the same fashion as was described for arrays.
>> c = a(1:2,2:3)
c =
1 2
5 8
An entire row or column can be referenced with a “ : ”. The instruction b(2,:)refers to row 2
of matrix b.
>> b(2,:)
ans =
0.2311 0.8913
>> b(:,2)
ans =
0.4860
0.8913
0.7621
Matrix Arithmetic
MATLAB uses the same arithmetic operators on matrices that it uses for evaluation. That is
because MATLAB stores all values as matrices.
- 14 -
>> a=rand(3),b=rand(3)
a =
ans =
The symbol “%” is used to mark a comment. MATLAB will ignore anything typed after the %
symbol (on the same line).
- 15 -
Most functions can be applied to matrices. Some functions that might be of interest include:
>> a
a =
>> norm(a)
ans =
1.8109
>> size(a)
ans =
3 3
>> [L U]=eig(a)
L =
U =
1.6175 0 0
0 0.4332 0
0 0 0.6121
>> [L U]=lu(a)
L =
1.0000 0 0
0.2433 1.0000 0
0.6387 0.5843 1.0000
- 16 -
U =
Given a linear matrix equation of the form Ax = b, it can be easily solved with MATLAB’s
\ - division. For example
2 3 x 2
5 4 y 12
>> A=[2 3; -5 4]
A =
2 3
-5 4
2
12
>> x=A\b
x =
-1.2174
1.4783
2.0000
12.0000
If A is singular (or nearly singular), you should use the rref function.
- 17 -
>> A=[ 2 -3 7;12 5 -13;-4 6 -14]
A =
2 -3 7
12 5 -13
-4 6 -14
21
-15
12
ans =
1.0e+016 *
0.1322
3.6347
1.5200
1.0000 0 -0.0870 0
0 1.0000 -2.3913 0
0 0 0 1.0000
Therefore the solution is a line that can be described by the parametric set C: x=0.0870t,
y=2.3913t, z=t, t is a Real number.
- 18 -
Special Matrices
MATLAB has several commands that will produce special matrices. Such commands include
ones() (matrix of 1s)
zeros() (matrix of 0s)
eye() (identity)
inv() (inverse)
det() (result is not a matrix) (determinant)
>> ones(3)
ans =
1 1 1
1 1 1
1 1 1
>> zeros(3,2)
ans =
0 0
0 0
0 0
Additional Variables
For most applications MATLAB variables will be assigned to numeric and/or string values. The
numeric values will usually be real or complex. With the addition of the Symbolic toolbox,
variables can also be declared as symbolic variables. This section will briefly describe some
aspects of working with complex and string variables.
Complex Numbers
MATLAB has fully integrated complex arithmetic. All variables are considered to be complex
and basic arithmetic operations perform correctly on both the real- and imaginary-part of
complex numbers. The imaginary unit is automatically assigned to i and j. A complex number
is entered as follows:
>> z = 1 + 2i
z =
1.0000 + 2.0000i
>> w = 1 – 2j
w =
1.0000 - 2.0000i
- 19 -
The i and j must appear at the end of the expression. Be careful not to accidentally reassign i
and j while working.
>> z+w
ans =
>> z-w
ans =
0 + 4.0000i
>> z*w
ans =
>> z/w
ans =
-0.6000 + 0.8000i
3.0000 + 4.0000i
>> abs(z)
ans =
>> angle(z)*180/pi
ans =
53.1300
Three other useful functions for working with complex numbers are real, imag and conj.
- 20 -
>> real(z),imag(z),conj(z)
ans =
3.0000
ans =
4.0000
ans =
3.0000 - 4.0000i
Strings
Strings are interpreted as arrays with character elements. String constants are enclosed in single
quotes.
Jonathon P. Smith
The last line above concatenates the three string variables with spacing and a period, and assigns
it to a new variable.
>> length(name)
ans =
17
>> first=name(1:8)
first =
Jonathon
>> last=name(13:17)
last =
Smith
- 21 -
Since strings are interpreted as arrays of characters, you can use some of the array functions
previously described on them (as shown above).
>> last'
ans =
S
m
i
t
h
Several strings can be stored in a matrix. But the strings must be the same length since each will
serve as a row of the matrix. To avoid adding additional spaces, you can use the str2mat
function.
>> name_matrix=str2mat(first_name,middle_initial,last_name)
name_matrix =
Jonathon
P
Smith
>> size(name_matrix)
ans =
3 8
A numeric value can be converted to a string with the num2str function. This conversion will
allow additional formatting with the sprintf function. The sprintf function parameters are
very similar to those used in the C language.
1.73205080756888
1.7321
- 22 -
>> sqrt3_str=num2str(sqrt3,20) % the 20 allows for 20 characters
sqrt3_str =
1.7320508075688772
Polynomials
MATLAB has several different functions for working with polynomials. Polynomials are entered
in as arrays of coefficients. (Note: insert 0s for missing terms.) The function roots() will
locate the zeros of the polynomial.
>> p = [1 2 3 4];
>> roots(p)
ans =
-1.6506
-0.1747 + 1.5469i
-0.1747 - 1.5469i
A polynomial can also be built from an array of roots using the poly() function.
>> P=poly(ans)
P =
You can evaluate a polynomial at a given value or list of values by using polyval(), for
example
yvalues =
4 6 10 16 24
Two polynomials can be convoluted (multiplied) using conv(p, q), or deconvoluted
(divided) using deconv(p, q).
- 23 -
>> Q=[2 -3 4];
>> P_Q=conv(P,Q)
P_Q =
Q =
R =
0 0 0 3
Partial fractions for a rational expression can be obtained using the residue() instruction, for
example
5x + 3
-------------
x^2 + 7x + 10
s =
-5
-2
Thus 5x + 3 22 1 7 1
------------- = -- ------- - - ------
x^2 + 7x + 10 3 (x + 5) 3 (x + 2)
- 24 -
Plotting Polynomials
MATLAB uses a simple plot technique where a set of domain values can be plotted against a set
of range values. The two sets do not necessarily create a function. Polynomials can be plotted in
the following manner:
4000
3500
3000
2500
2000
1500
1000
500
0
0 5 10 15
Plots
MATLAB is a very powerful visualization tool that can produce many 2-dimensional and 3-
dimensional plots, as well as animation. You can produce publication quality plots wit the
formatting tools.
The data for plotting can be stored in vectors, matrices, and external data files, or defined by
analytic functions.
Line Plots
A basic 2-D plot is a line plot of one variable versus another. Below are a few examples.
>> x = -2*pi:pi/12:2*pi;
>> y=sin(x);
- 25 -
>> plot(x,y)
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
-8 -6 -4 -2 0 2 4 6 8
>> y=cos(x);
>> plot(x,y,'--') % the '--' indicates a broken line
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
-8 -6 -4 -2 0 2 4 6 8
>> y=sin(x);
>> y2=cos(x);
>> % plot both sin(x) and cos(x) on the same plot
>> plot(x,y,x,y2,'--')
- 26 -
1
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
-8 -6 -4 -2 0 2 4 6 8
>> x=rand(1,10);
>> y=rand(1,10);
>> % produces a scatter plot using o to mark the points
>> plot(x,y,'o')
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
There are several formatting features that can be used to dress up a plot. These include:
title(string)
xlabel(string)
ylabel(string)
- 27 -
legend(string 1, string 2, …)
text(x, y, string)
axis([x_min x_max y_min y_max])
grid (choose either on or off)
>> x = -2*pi:pi/12:2*pi;
>> y=sin(x);
>> y2=cos(x);
>> plot(x,y,x,y2,'--')
>> title('sin(\theta) & cos(\theta)')
>> xlabel('\theta in radians')
>> legend('sin(\theta)','cos(\theta')
>> grid
sin() & cos()
1
sin()
0.8
cos(
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
-8 -6 -4 -2 0 2 4 6 8
in radians
To learn more about the plotting functions listed above perform a help on each. Over 75
symbols can be included in text strings. This can be accomplished by embedding a subset of
TEX commands in the string. There is also a limited set of TEX formatting commands available.
They include ^ and _ for superscripts and subscripts, respectively. Also included are
\fontname
\fontsize
\bf (boldface)
\it (italic)
\sl (slant)
\rm (Roman)
- 28 -
Subplots
You can place more than one plot on a figure using the subplot function. The function takes
three arguments.
n_rows and n_cols serve to divide the figure into fields. The fields are numbered from left
to right and then up to down. which_plot tells which field to place a plot.
>> x=linspace(0,10,100);
>> y1=log(x);y2=log(2*x);
Warning: Log of zero.
Warning: Log of zero.
>> y3=log(3*x);y4=log(4*x);
Warning: Log of zero.
Warning: Log of zero.
>> subplot(2,2,1)
>> plot(x,y1), title('y=ln(x)')
>> subplot(2,2,2)
>> plot(x,y2), title('y=ln(2x)')
>> subplot(2,2,3)
>> plot(x,y3), title('y=ln(3x)')
>> subplot(2,2,4)
>> plot(x,y4), title('y=ln(4x)')
y=ln(x) y=ln(2x)
4 4
2
2
0
0
-2
-4 -2
0 5 10 0 5 10
y=ln(3x) y=ln(4x)
4 4
2 2
0 0
-2 -2
0 5 10 0 5 10
- 29 -
Surface Plots
There are several choices for plotting z = f(x,y). The most common ways are to use mesh
and surf. When defining a function of two independent variables, you need to first set up a
rectangular domain. You use meshgrid for this.
>> mesh(x,y,z);
>> xlabel(‘x-axis’); ylabel(‘y-axis’); zlabel(‘z-axis’)
>> grid on
400
300
z-axis
200
100
0
10
5 10
0 5
0
-5 -5
y-axis -10 -10
x-axis
- 30 -
400
300
200
100
0
10
10
5 5
0
-5
0 -10
You can change the viewing angles for a 3-D plot with view(azimuth,elevation). The
default angles are -37.5° and 15°. The azimuth is taken from the positive x-axis and the elevation
is from the xy-plane.
>> view(45,30)
400
300
z-axis
200
100
0
-10 10
-5 8
6
0
4
5 2
10 0
y-axis
x-axis
- 31 -
Contour Plots
Level curves of a surface can be produced with the contour function. It has several different
forms that include:
>> contour(x,y,z,[0:50:350])
10
0
-10 -8 -6 -4 -2 0 2 4 6 8 10
Contour plots can be combined with surface plots by appending a c on the end of mesh or
surf.
- 32 -
400
300
200
100
0
10
10
5 5
0
-5
0 -10
Symbolic Algebra
MATLAB uses the MapleTM kernel to perform symbolic algebra.
If you wish to perform symbolic algebra, you must first declare the variables you are going to
use in expressions as symbolic variables. This is done by using the sym command.
>> sym x t y
Expressions containing the symbolic variables will be considered a symbolic object that can be
manipulated.
>> syms x
>> f=x^3+3*x^2+3*x+1
f =
x^3+3*x^2+3*x+1
>> pretty(f)
3 2
x + 3 x + 3 x + 1
- 33 -
>> F=factor(f)
F =
(x+1)^3
>> collect(F)
ans =
x^3+3*x^2+3*x+1
>> simple(f)
simplify:
x^3+3*x^2+3*x+1
radsimp:
x^3+3*x^2+3*x+1
combine(trig):
x^3+3*x^2+3*x+1
factor:
(x+1)^3
expand:
x^3+3*x^2+3*x+1
combine:
x^3+3*x^2+3*x+1
convert(exp):
x^3+3*x^2+3*x+1
convert(sincos):
x^3+3*x^2+3*x+1
convert(tan):
x^3+3*x^2+3*x+1
- 34 -
collect(x):
x^3+3*x^2+3*x+1
mwcos2sin:
x^3+3*x^2+3*x+1
ans =
(x+1)^3
>> F
F =
(x+1)^3
>> expand(F)
ans =
x^3+3*x^2+3*x+1
>> g=F/(x^2-2*x+1)
g =
(x+1)^3/(x^2-2*x+1)
>> pretty(g)
3
(x + 1)
------------
2
x - 2 x + 1
>> pretty(factor(g))
3
(x + 1)
--------
2
(x - 1)
>> expand(g)
ans =
1/(x^2-2*x+1)*x^3+3/(x^2-2*x+1)*x^2+3/(x^2-2*x+1)*x+1/(x^2-
2*x+1)
- 35 -
>> pretty(expand(g))
3 2
x x x 1
------------ + 3 ------------ + 3 ------------ + ------------
2 2 2 2
x - 2 x + 1 x - 2 x + 1 x - 2 x + 1 x - 2 x + 1
>> pretty(simplify(g))
3
(x + 1)
------------
2
x - 2 x + 1
>> g
g =
(x+1)^3/(x^2-2*x+1)
>> limit(g,-1)
ans =
>> limit(g,1)
ans =
Inf
3*(x+1)^2/(x^2-2*x+1)-(x+1)^3/(x^2-2*x+1)^2*(2*x-2)
>> pretty(gp)
2 3
(x + 1) (x + 1) (2 x - 2)
3 ------------ - ------------------
2 2 2
x - 2 x + 1 (x - 2 x + 1)
- 36 -
>> pretty(simplify(gp))
2
(x + 1) (x - 5)
----------------------
2
(x - 1) (x - 2 x + 1)
>> syms y
>> h=sin(x*y)
h =
sin(x*y)
hx =
cos(x*y)*y
-sin(x*y)*x*y+cos(x*y)
-1/x*(sin(x*y)-x*y*cos(x*y))+1/x*sin(x*y)
>> simplify(hx)
ans =
cos(x*y)*y
You can plot a symbolic object in one variable using the instruction ezplot.
>> hx = simplify(hx);
>> ezplot(hx)
- 37 -
cos(x y) y = 0
6
0
y
-2
-4
-6
-6 -4 -2 0 2 4 6
x
cos(x y) y = 0
10
5
y
0
0 1 2 3 4 5 6 7 8 9 10
x
- 38 -
MATLAB Programming Basics
MATLAB integrates a high-level programming language into an interactive environment that
lets you quickly develop and analyze algorithms. The MATLAB language’s main data type is a
matrix. Vectors and matrices are integral to scientific computing and problem solving making
MATLAB is an excellent choice for such tasks. Use of vectors and matrices can also greatly
reduce the amount of code necessary to solve scientific problems. Less code also means less run-
time.
Script Files
There is no doubt that you can do a lot of work in the command window. However, when the
amount of instructions needed to complete a task increases or you need to re-execute a block of
instructions several times, the command window is a poor choice. The best choice is to write a
MATLAB program.
MATLAB programs are stored as text files. The files can be loaded into the MATLAB command
environment where they are then interpreted and executed. MATLAB supports two types of
programs: script files and function files. Script files consist of sequences of instructions stored in
text files. The files are commonly referred to as m-files because of the .m extension used.
m-files
m-files consist of lists of MATLAB instructions stored as a text file. An m-file can be created by
any text editor or word processor. If a word processor is used, make sure to save the file as a text
file. MATLAB has its own built-in text editor. To launch it, type the command edit in the
command window.
- 39 -
The use of the editor is pretty straight-forward. The advantage of using MATLAB’s editor is that
color coding and formatting is built in. Built-in commands and functions appear as blue,
comments appear as green and strings show up as purple. Flow structures are automatically
indented.
Another advantage of using an m-file is that m-files have access to all variables in the current
workspace and all variables created by m-files are stored in the workspace. You could use an m-
file to set constants that will be needed during a work session. Suppose that you are working on
fluid mechanics and the ideal gas law ( p RT , where R is the gas constant). You could write
a script that would set R for common gases.
The command above will launch the MATLAB editor and open the file gas_constants if it exists.
If the file does not exist, MATLAB will ask you if you would like to create it.
R_air = 2.869e+2;
R_cd = 1.889e+2;
R_he = 2.077e+3;
R_h = 4.124e+3;
R_me = 5.183e+2;
R_n = 2.968e+2;
R_o = 2.598e+2;
Once the m-file is created and saved, you execute it by typing the name of the script (without the
.m extension) in the command window.
>> gas_constants
Type the command who to see that the constant have been set.
>> who
Your variables are:
- 40 -
% Sine & Cosine Plot
%
% The following script plots both the y = sin(x) and y = cos(x)
% over the range from -2*pi and 2*pi. The graph is formatted and
% a legend is displayed.
x = -2*pi:pi/12:2*pi;
y=sin(x);
y2=cos(x);
plot(x,y,x,y2,'--')
title('\fontname{times} \fontsize{16} sin(\theta) & ...
cos(\theta)')
xlabel('\fontname{times} \fontsize{16} \theta in radians')
legend('\fontname{times} \fontsize{10} sin(\theta)', ...
'\fontname{times} \fontsize{10} cos(\theta')
axis([-2*pi 2*pi -1.5 1.5])
grid
0.5
-0.5
-1
-1.5
-6 -4 -2 0 2 4 6
in radians
Side Effects
The advantage of being able to set variables using an m-file is also a major drawback. If you
already have variables in the workspace with the same names as those in a script, the script will
replace the values. Perhaps that is what you want to have happen, usually it isn’t.
In the sine and cosine plot above, the variables x , y and y2 were added to the workspace and
could very easily overwritten pre-existing values of those variables.
- 41 -
Comments
The two scripts above made use of comment statements. Comments consist of the characters
between the % symbol and the end of the line. The % symbol can appear anywhere within an
instruction line. Comments were made any several examples in the first chapter of this manual.
Multiple lines of comments must each begin with a % symbol.
The % can also be used to “hide” programming statements from the interpreter. This is a
common practice when debugging code.
It is very important to fully document any program that you code. This will be brought up in the
next chapter.
Function Files
A function file is a hybrid script file that also uses a .m extension. A function file (or simply a
function) is analogous to a Fortran subroutine or a C function. Functions are code modules that
can communicate with the MATLAB command window and each other. A function utilizes a
predefined list of input and output arguments. A MATLAB function is easier to work with than
functions in other languages (e.g. C-language). A MATLAB function can output more than one
matrix (remember that the matrix is MATLAB’s data type) where as in a C program you can
output only one value and would have to use pointers to manipulate the elements of a matrix.
Variables that are used in a function are considered local and are invisible to other functions and
the command window. If you want a function to be used by another function or the command
window you can include it as an output argument. The values of output arguments are sent to the
workspace. Another option is to use a global variable. Care should be taken when using global
variables. Global variables should not be used when input and output arguments can accomplish
the same task. No further discussion of global variables will be made.
Syntax
The main syntax issue of a function is the definition line. The definition line of a function must
be the first instruction line and follow the following form
where the output list is comma separated and enclosed by brackets ([ ]), and the input list is
comma separated and enclosed in parentheses ( ). Both lists are optional. The function name
must follow the variable conventions described in the first chapter. You should save a function
under the name used in the definition line.
A function with no input or output list is referred to as a null function. Null functions can be used
in lieu of m-files without fear of inadvertently changing variable values.
- 42 -
%% Cosine & Sine Plot Function
%%
%% The following script plots both the y = sin(x) and y = cos(x)
%% over the range from -2*pi and 2*pi. The graph is formatted
%% and a legend is displayed.
function cosine_sine_plot
x = -2*pi:pi/12:2*pi;
y=sin(x);
y2=cos(x);
plot(x,y,x,y2,'--')
title('\fontname{times} \fontsize{16} sin(\theta) &
cos(\theta)')
xlabel('\fontname{times} \fontsize{16} \theta in radians')
legend('\fontname{times} \fontsize{10} sin(\theta)', ...
'\fontname{times} \fontsize{10} cos(\theta')
axis([-2*pi 2*pi -1.5 1.5])
grid
>> clear
>> who
>> cosine_sine_plot
>> who
>>
As mentioned previously the input and output lists can be of any length. The arguments in either
list can be numeric- or a string-valued. In most applications you will know what arguments you
want to feed to a function and which arguments you want a function to return. You can also call
a function with fewer input or output arguments than listed. nargin and nargout are
variables available to a function that stores the number of arguments fed to the function and the
number of output arguments being requested. Both variables are used to help make a function
robust.
In some cases you may not know the number of arguments to feed a function or to send back to
the command window. You can use vargin and vargout in those cases. Both are arrays that
store the input and output arguments. You can access each argument with an index, i.e.
vargin(1).
You can also include a function as an input argument. The name of the function is passed as a
string.
- 43 -
Primary and Secondary Functions
The functions as so far described are primary functions and are accessible to any other function
and/or the command window. A secondary or sub-function can be included with a primary
function and will be seen only by the primary function. Secondary functions appear at the end of
a primary function.
- 44 -
%% ----------- Secondary Function --------------
%% --------------- (Reactions)------------------
function R=reactions(b,P)
R=[0 0]';
M=P(2)*(b/2)+P(3)*b;
R(2)= M/b;
R(1)= sum(P)-R(2);
function [A b]=matrices(theta, R, P)
c=cos(theta); s=sin(theta);
A=[c c 0 ;s 0 0; -c 0 c;];
b=[0 0 0]';
b(2)=P(1)-R(1);
- 45 -
>> P=100*ones(3,1);
>> f = truss(12, 30, P)
f =
-100.0000
100.0000
-100.0000
User Input
The input function is used to prompt users for information. The input data can be either
numeric- or string-valued and is entered via the keyboard. The function expects a numeric-
valued argument.
MATLAB will display the prompt and wait for a value or matrix to be entered. If you want a
string ( such as a name of a function) you must include a second argument which is 's'.
Text Output
There are three main functions for printing output. The first is the low-level function disp. It
will display the value of a variable or a string.
The advantage of using display is that it does not show the variable name on the screen. Draw
back is that the display formatting is handled by the format command, which is limited.
*
This example and many others in this chapter are shown as command window instructions in order to demonstrate
their results. All MATLAB instructions can be part of an m-file or function.
- 46 -
Two functions that are available in MATLAB are sprintf and fprintf. Both functions can
be used to print formatted output to the screen. The first function sprintf is intended to
convert data to a string.
1.61803398874989
1 16
2.2204e-016
0.0000000000000002220446049
4.5036e+015
4503599627370496.00000
The formatting (conversion) specifications used are similar to those used in the C-language.
Conversion specifications are pefaced with the character % and involve optional flags, optional
width and precision fields, optional subtype specifier, and conversion characters d, i, o, u, x, X,
f, e, E, g, G, c, and s. Refer to a C-language manual for complete details. The special formats
\n,\r, \t,\b, and \f can be used to produce linefeed, carriage return, tab, backspace, and
formfeed characters respectively. Use \\ to produce a backslash character and %% to produce
the percent character.
Remember that your data is now stored as a string. If you need to convert back to numeric-
valued data, use the str2num function. The function takes the string and converts it to a matrix
- 47 -
of numeric values. The string you wish to convert must consist of only numeric characters.
MATLAB uses the eval function to interpret strings.
>> str='(1+sqrt(5))/2'
str =
(1+sqrt(5))/2
>> eval(str)
ans =
1.61803398874989
>>
The last function is fprintf. This function formats data and streams it to a file. If you omit the
file name as an argument, the data is streamed to the command window. A noticeable difference
between sprintf and fprintf is that fprintf does not assign and display a variable
name.
>> fprintf('string');
string
>> fprintf('%0.15g',(1+sqrt(5))/2)
1.61803398874989
2.2204e-016
0.0000000000000002220446049
4.5036e+015
- 48 -
4503599627370496.00000
The same formatting specifications used with sprintf are used. Refer to the previous
description.
Previously it was mentioned that the filename must be omitted in order to print to the command
window. The example below shows how to print formatted text to a file named data.dat.
>> x=[1:10]’;
>> fout=fopen('data.dat','wt');
>> fprintf(fout,' k x(k)\n');
>> for k=1:length(x)
fprintf(fout,'%4d %5.2f\n',k,x(k));
end
>> fclose(fout);
You can see the contents of any .m, or .dat with the type command. To view an m-file you do
not need to include the .m extension.
u = u(:).'; v = v(:).';
nu = length(u); nv = length(v);
if nu < 2, up = 0; else up = u(1:nu-1) .* (nu-1:-1:1); end
if nv < 2, vp = 0; else vp = v(1:nv-1) .* (nv-1:-1:1); end
a1 = conv(up,v); a2 = conv(u,vp);
i = length(a1); j = length(a2); z = zeros(1,abs(i-j));
if i > j, a2 = [z a2]; elseif i < j, a1 = [z a1]; end
- 49 -
if nargout < 2, a = a1 + a2; else a = a1 - a2; end
f = find(a ~= 0);
if ~isempty(f), a = a(f(1):end); else a = zeros(superiorfloat(u,v));
end
b = conv(v,v);
f = find(b ~= 0);
if ~isempty(f), b = b(f(1):end); else b = zeros(class(v)); end
k x(k)
1 1.00
2 2.00
3 3.00
4 4.00
5 5.00
6 6.00
7 7.00
8 8.00
9 9.00
10 10.00
Flow Control
A great majority of algorithms require conditional execution of blocks of code and/or iterative
processes applied to blocks of code. The MATLAB language provides the same basic flow
control as other high-level languages.
Relational and logical operators are used to form logical statements that can be determined true
or false. True statements are assigned a value of 1 and false statements are assigned a value of 0.
- 50 -
Some of the relational and logical operators available are listed in the table below.
All non-zero real-values are considered true and 0 is the only value considered false. Complex
numbers, NaN, and Inf cannot be converted to a truth value of 0 or 1.
2 4 5
Function Definition
isvector(variable) Is true if the variable represents a vector
Is true if the variable represents a single
isscalar(variable)
element array
isnumeric(variable) Is true if all elements are numeric
Is true if variable has been assigned to [ ] (the
isempty(variable)
empty set)
Is true if the variable represents a string
ischar(variable)
character
Is true if the variable has been assigned to not a
isnan(variable)
number, e.g. 0/0
Is true if the variable has been assigned to
isinf(variable)
infinity, e.g. 1/0
isfinite(variable) Is true if the variable represents a finite value
- 51 -
ans =
>> isvector(A)
ans =
>> isvector([])
ans =
>> isempty([])
ans =
c =
>> isnan(c)
ans =
0 0 1 0 0
Operator Precedence
There are three types of operators, 1) arithmetic, 2) relational, and 3) logical. The order of
precedence for the operators is the same as the list above, i.e. arithmetic operators have the
highest precedence. The order of arithmetic operations was discussed in the first chapter. A more
complete hierarchy is shown below. Operators of the same precedence are grouped together
between bold lines.
- 52 -
Operator Definition
.’ Elemental transposition
.^ Elemental power
‘ Matrix ransposition
^ Matrix power
+ Unary positive
- Unary negative
.* Elemental multiplication
./ Elemental division
.\ Elemental backward division
* Multiplication
/ Division
\ Backward division
+ Addition
- Subtraction
: Colon vector operator
if … else … Statements
The main MATLAB decision construct is the if … else … statement. There are several
variations of it. The simplest has the form
if (logical statement)
block of code to execute if logical statement is true
end
- 53 -
Other possible forms are
if (logical statement)
block of code to execute if logical statement is true
else
block of code to execute if logical statement is false
end
if (logical statement 1)
block of code to execute if logical statement 1
is true
elseif (logical statement 2)
block of code to execute if logical statement 2
is true
.
.
.
elseif (logical statement n)
block of code to execute if logical statement n
is true
else
block of code to execute if all logical statements
are false
end
switch Statements
- 54 -
.
case value_n
block of code to execute if the evaluative expression
is value_n
otherwise
block of code to execute if the evaluative expression
is not any of the values
end
for-Loops
Iteration is prevalent in many programs and numeric routines. One of the most popular iteration
constructs is a for-loop. The loop utilizes an index that typically counts from a starting value to
an ending value and is used in a block of statements. The block is executed for each index value.
Recursive definitions are natural examples for using a for-loop.
function f=fibonacci(N)
N=ceil(N);
f=ones(N,1);
f(1)=1;
f(2)=1;
for index=3:N
f(index)=f(index-2)+f(index-1);
end
- 55 -
>> f=fibonacci(4.3)
f =
1
1
2
3
5
while-Loops
The second most commonly used loop construct is the while-loop. This loop continues to
execute a block of instruction until a condition is met. In several algorithms for solving nonlinear
equations a block of instructions continues to be executed until a predetermined tolerance is met.
len_eq=length(eq);
if eq(1)~='x'
error('The equation must begin with x =');
end
if nargin<3
tol=0.001;
- 56 -
end
if nargin <2
x1=0;
end
n=1;
while eq(n)~='='
n=n+1;
end
n=n+1;
equation = eq(n:len_eq);
n=1; x=x1; X(n)=x;
X(n+1)=eval(equation);
while abs(X(n+1)-X(n))>tol
n=n+1;x=X(n);
X(n+1)=eval(equation);
end
x=X';
break
When using a while-loop it is necessary to provide a “break”. Without a “break,” the stopping
condition may never be reached creating an infinite loop. The break command stops execution
of a loop and transfers the interpreter to the first instruction line directly after the end of the
loop.
The break command can also be used when two or more stopping conditions are necessary. For
example the previous fixed routine could be modified to incorporate a maximum number of
iterations as a stopping mechanism. This is very common in routines of this type.
max_n=25;
while n<max_n-1
n=n+1;x=X(n);
X(n+1)=eval(equation);
if abs(X(n)-X(n-1))<=tol
break;
end
end
- 57 -
return
The return command is very similar to the break command in the sense that it stops
execution. However, the return command transfers control back to the calling function or
command window, whereas the break command transfers control to the first instruction
directly after the loop in the function it appears. Any code that follows the execution of a
return command is not interpreted.
Vectorization
Vectorization refers to the process of transforming code that operates on scalars to code that
operates on vectors. This type transformation makes code more efficient and the operations will
be performed more quickly by MATLAB. Vector operations are performed using optimized
binary code that is part of the MATLAB kernel.
Copying
Vectorization makes copying elements from one vector or matrix to another more efficient as
well. A common need when solving a system of linear equations iteratively is to create the
matrices L, D, and U for a square matrix A such that L + D + U = A.
- 58 -
%% such that A = L + D + U
%%
%% usage [L D U]=decomp_mat(A)
%%
%% Input:
%% A - Square matrix
%%
%% Output:
%% L - Lower triangular matrix
%% D - Diagonal matrix
%% U - Upper triangular matrix
function [L D U]=decomp_mat(A)
[m n]=size(A);
if m ~= n
error('The matrix A must be square!');
end
I=eye(m);
D=A.*I;
L=zeros(m);
for k = 2:m
L(k,1:k-1)=A(k,1:k-1);
end
U=A-D-L;
>> A=rand(4)
A =
>> [L D U]=decomp_mat(A)
L =
0 0 0 0
0.9169 0 0 0
0.4103 0.8132 0 0
0.8936 0.0099 0.6038 0
- 59 -
D =
U =
0 0 0 0
-0.9169 0 0 0
-0.4103 -0.8132 0 0
-0.8936 -0.0099 -0.6038 0
The decomp_mat routine does make use of a for-loop, but it also uses vectorization to copy
rows from the given matrix A to the matrix L. D and U are found through matrix operations.
Pre-allocating Memory
You do not need to pre-allocate memory since a MATLAB matrix is a dynamic data structure.
Although, initializing a matrix or vector (especially inside a loop) makes code perform more
efficiently. The functions ones, zeros, and eye are used for initializing a matrix. The zeros
function was used in the decomp_mat routine.
Global Variables
Global variables are used to forgo with input and output arguments. A global variable is seen by
all functions and can subsequently be manipulated by all functions. Global variables should not
be used when input and output arguments can accomplish the needed task.
- 60 -
A variable can be made global by a declaration statement (global variable_name) in the
command window or any function. The declaration must appear in each function that wishes to
use the variable.
feval
Many applications involve user-defined functions that need to be evaluated. The functions are
usually single- or multi-variable functions. The feval function is used to evaluate these.
function c=funn(r)
R=8;K=1;
B1=3;B2=1;
c1=(R.*r.^2)./(4*K);
c2=B1.*log(r); % log is the natural log
c=c1+c2+B2;
>> r=[1:5]';
>> clear c
>> c=feval('funn',r)
c =
3.0000
11.0794
22.2958
37.1589
55.8283
Inline Functions
If a function definition is not too long or complicated, it can be defined as an inline function.
Inline functions are evaluated by passing values to them directly.
- 61 -
>> funn=inline('(cosh(x)).^2+(sinh(x)).^2;')
funn =
Inline function:
funn(x) = (cosh(x)).^2+(sinh(x)).^2;
>> funn(1)
ans =
3.7622
>> x=-2:2;
>> funn(x)
ans =
- 62 -
Numerical Problem Solving Basics
Numerical problem solving (or scientific computing) involves a marriage of application,
computation and mathematics. It is a form of scientific investigation done by formulating
mathematical models whose solutions are approximated by computer simulations. A consistent
and orderly approach to the formulation of models is important. The approach should be general
enough to be applicable to all fields of study. An engineering methodology will be used.
Report of Solution
The report of the solution to a problem should be organized. A common organization of the
report contains five parts:
1. Problem Statement
2. Find Statement
3. Given Statement
4. Work
5. Results
Work
Work involves both hand calculations and computer calculations. Computer calculations consist
of work done in the MATLAB command window as well as the development of a MATLAB
function (or functions).
Stepwise Refinement
When developing mathematical model for a problem or when developing a MATLAB function,
you should perform what is known as stepwise refinement. Stepwise refinement involves
breaking down a larger task into smaller tasks. Each smaller task is then further broken down
into smaller modules that have obvious solutions or can be easily tested in the MATLAB
command window. The smaller modules are then solved or coded. If they are coded then they
and incorporated as part of a MATLAB function.
- 63 -
You should use a consistent style when developing a function.
function declaration
Prologue
Computational tasks
The location of the function declaration can be either at the top or directly below the
prologue.
Prologue
The prologue is the documentation of the function. The prologue should closely follow
MATLAB conventions. An example of a function prologue is shown below.
- 64 -
%% D - Diagonal matrix
%% U - Upper triangular matrix
The main part of the prologue consists of 1) the function name, 2) a synopsis of the function, 3)
usage of the function, 4) input arguments, and 5) output arguments. MATLAB uses the first
unbroken comment block of a function in its help system. Therefore it is important to keep the
main portion of the prologue together. Use % for spacing.
The second portion of the prologue is the credits. It is separated from the main portion by a
space. It should contain information about the programmer and date of the original code. If the
function is revised at a later date, the date of the revision should be included in the credits. The
credits are not displayed when using MATLAB’s help.
Visual Blocking
Visual consistency is an important part of a programming style. MATLAB’s text editor helps
with this. It will automatically indent blocks in flow control constructs. It also color codes
different aspects of the code.
You can also insert white spaces in your code. White spaces visually groups related lines of code
together.
- 65 -
Good Bad
max_n=25; max_n=25;
while n<max_n-1
while n < max_n-1 n=n+1;x=X(n);
n = n+1; X(n+1)=eval(equation);
x = X(n); if abs(X(n)-X(n-1))<=tol
X(n+1)=eval(equation); break;
if abs(X(n)-X(n-1))<=tol end
break; end
end
end
Comments
Use comments within the code sections to help break it apart and clarify the code’s purpose.
function f=fibonacci(N)
N=abs(N);
N=ceil(N);
f=ones(N,1);
f(1)=1;
f(2)=1;
- 66 -
% Recursive definition for the rest of the sequence
for index=3:N
f(index)=f(index-2)+f(index-1);
end
Robust Programming
Robust programming means that you develop code to handle user ignorance. For example, the
user entered a fraction when an integer is expected. Another example, a function requires three
input arguments but the user only provides two. When developing a MATLAB function you
should do the following:
Never assume that input data are correct. Check that the proper type of data is inputted.
Check to see that all the needed data is supplied.
Guard against the occurrence of conditions that could prevent correct calculations.
Use a default condition for if … ifelse … else and switch constructs.
Use error messages to help determine why a function failed.
When the error function is encountered a message is displayed and control is returned to the
command window or calling function.
[m n] = size(A);
if m ~= n
error('The matrix A must be square!');
end
Problem Examples
Four examples of solved problems follow. The problems are typical for beginning study in
numerical problem solving (scientific computing).
Nonlinear Equations
Systems of Linear Equations
Curve Fitting and Function Approximations
Differentiation and Integration
- 67 -
Nonlinear Equation
-1
-2
-3
-4
-5
-5 -4 -3 -2 -1 0 1 2 3 4 5
- 68 -
Algorithm
- 69 -
Computer Routine
x=X';
- 70 -
Test Routine
>> g=inline('0.5*(x+3./x)')
g =
Inline function:
g(x) = 0.5*(x+3./x)
>> x=fixed(g,1)
x =
1.00000000000000
2.00000000000000
1.75000000000000
1.73214285714286
1.73205081001473
>> x=fixed(g,-1)
x =
-1.00000000000000
-2.00000000000000
-1.75000000000000
-1.73214285714286
-1.73205081001473
Results
- 71 -
Linear System
30
25
20
15
10
-5
-10
-15
-5 -4 -3 -2 -1 0 1 2 3 4 5
- 72 -
Algorithm
Computer Routine
- 73 -
%% Date: 01/05/07
max_n=25;
if nargin < 3
tol=0.001;
end
if nargin < 2
x1=0;
end
if nargin < 1
error('usage: X=fixedsys(funn, x1, tolerance)');
end
x(1)=x1;
[x(2) y(1)]=feval(funn,x(1));
n=2;
x=x(1:length(x)-1);
X=[x' y'];
Test Routine
function [x y]=funn(x)
y=(x+9)/5;
x=(6-y)/4;
- 74 -
>> X=fixedsys('funn',0,0.0001)
X =
0 1.80000000000000
1.05000000000000 2.01000000000000
0.99750000000000 1.99950000000000
1.00012500000000 2.00002500000000
0.99999375000000 1.99999875000000
1.00000031250000 2.00000006250000
Results
Note: The routine developed for this system of linear equations would work for other 2x2
systems.
- 75 -
Curve Fitting
- 76 -
Hand work in command window
5500
5000
4500
4000
3500
3000
2500
2000
1500
1000
500
0
0 1 2 3 4 5 6 7 8 9 10
>> u=t;
>> v=log(5000./P-1);
>> M=[sum(u.^2) sum(u);sum(u) length(u)]
M =
30 10
10 5
C =
-2.3703
2.8718
>> p=inv(M)*C
p =
-0.8114
2.1971
>> PP=inline('5000./(1+8.9991*exp(-0.8114*t))')
- 77 -
PP =
Inline function:
PP(t) = 5000./(1+8.9991*exp(-0.8114*t))
>> PP(5)
ans =
4.3264e+003
Computer Routine
function population
su=sum(u);
M=[sum(u.^2) su;su length(u)];
b=[sum(u.*v) sum(v)]';
X=inv(M)*b;
A=X(1);
B=X(2);
C=exp(B);
% Find P(5)
P_5=feval('P',A,C,L,5)
x= 0:0.5:10;
- 78 -
y=feval('P',A,C,L,x);
plot(t,pop,'o',x,y);
title('Population Growth')
xlabel('time')
legend('Data','Approximation')
function p=P(A,C,L,t)
p=L./(1+C.*exp(A.*t));
Test Routine
>> population
0 500
1 1000
2 1800
3 2800
4 3700
P_5 =
4.3264e+003
Population Growth
5000
4500
4000 Data
Approximation
3500
3000
2500
2000
1500
1000
500
0 1 2 3 4 5 6 7 8 9 10
time
- 79 -
Results
5000
The population model is P (t )
1 8.991e 0.8114 t
P(5) = 4.3264e+003
Note: You could easily change the data at the start of the routine to suit another situation. You
could also make the routine a function that is passed t, y, and L.
- 80 -
Numerical Integration
- 81 -
Hand example in command window
>> f=inline('1./x.^3')
f =
Inline function:
f(x) = 1./x.^3
>> plot(x,f(x))
Warning: Divide by zero.
> In inlineeval at 13
In inline.subsref at 25
>> axis([0 4 0 10])
>> axis([0 4 0 3])
>> axis([0 4 0 1.5])
>> grid
1.5
0.5
0
0 0.5 1 1.5 2 2.5 3 3.5 4
>> a=1
a =
>> b=3
b =
- 82 -
>> h=b-a
h =
>> I=(h/2)*(f(a)+f(b))
I =
1.0370
>> 28/27
ans =
1.0370
Computer Routine
function dIntegral
% set parameters
x=0:0.1:4;
plot(x,f(x));
axis([0 4 0 1.5])
grid
% display result
c=a+(b-a)/2;
h=h/2;
x=[a c b];
I2=(h/2)*sum((f(x(1:2))+f(2:3)))
- 83 -
Test Routine
>> dIntegral
Warning: Divide by zero.
> In inlineeval at 13
In inline.subsref at 25
In dIntegral at 13
I1 =
28/27
I2 =
139/216
Results
1 3
The approximation of dx is 28/27
1 x3
- 84 -
References
Beer and Johnston (2007). Vector Mechanics for Engineers: Statics and Dynamics, 8E.
McGraw-Hill Companies, Inc.: Boston, MASS. (ISBN: 978-0-07-297698-4 – 0-07-321222-9)
Biran, Adrian and Breiner, Moshe (1995). MATLAB for Engineers. Addison-Wesley Publishing:
Reading, MASS. (ISBN: 0-201-56524-2)
Burden, Richard L. and Faires, J. Douglas (1997). Numerical Analysis, 6E. Brooks/Cole
Company: Pacific Grove, CA. (ISBN: 0-534-95532-0)
Etter, D.M. (1993). Engineering Problem Solving with MATLAB. Prentice-Hall: Upper Saddle
River, NJ. (ISBN: 0-13-280470-0)
Faires, J. Douglas and Burden, Richard L. (1998). Numerical Methods, 2E. Brooks/Cole
Company: Pacific Grove, CA. (ISBN: 0-534-35187-5)
Fausett, Laurene (1999). Applied Numerical Analysis using MATLAB. Prentice-Hall: Upper
Saddle River, NJ. (ISBN: 0-13-319849-9)
Gerald and Wheatley (2004. Applied Numerical Analysis, 7E.. Addison-Wesley Publishing:
Reading, MASS. (ISBN: 0-321-13304-8)
Kernighan, B.W. and Ritchie, D.M. (1988). The C Programming Language, 2E. Prentice-Hall:
Upper Saddle River, NJ. (ISBN: 0-13-110362-8)
Larson, Hostetler and Edwards (1999). Calculus, Early Transcendental Functions, 2E. Houghton
Mifflin Company: Boston, MASS. (ISBN: 0-395-93320-X)
Maron, M.J. (1987). Numerical Analysis: A Practical Approach, 2E. Macmillan Publishing
Company: New York. (ISBN: 0-02-376210-1)
Munson, Young and Okiishi (2006). Fundamentals of Fluid Mechanics, 5E. John Wiley & Sons,
Inc.: Hoboken, NJ. (ISBN: 0-471-67582-2)
Press, W.H., et al (1992). Numerical Recipes in C: The Art of Scientific Computing, 2E.
Cambridge University Press: Cambridge, UK. (ISBN: 0-521-43108-5)
- 85 -
Vetterling, W.T, et al (1992). Numerical Recipes: Example Book [C], 2E. Cambridge University
Press: Cambridge, UK. (ISBN: 0-521-43720-2)
White, Robert E. (2004). Computational Mathematics: Models, Methods, and Analysis with
MATLAB and MPI. Chapman & Hall/CRC: Boca Raton, FL. (ISBN: 1-58488-364-2)
- 86 -