A Practical Introduction To Matlab - Updated For Matlab 5
A Practical Introduction To Matlab - Updated For Matlab 5
Contents
1 Introduction 2
2 Simple calculations and graphs 2
2.1 Entering vectors and matrices; built-in variables and functions;
help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 Arithmetic operations on matrices . . . . . . . . . . . . . . . . . 7
2.3.1 Standard operations . . . . . . . . . . . . . . . . . . . . . 7
2.3.2 Solving matrix equations using matrix division . . . . . . 9
2.3.3 Vectorized functions and operators; more on graphs . . . 10
2.4 Some miscellaneous commands . . . . . . . . . . . . . . . . . . . 11
3 Programming in Matlab 13
3.1 Conditionals and loops . . . . . . . . . . . . . . . . . . . . . . . . 14
3.2 Scripts and functions . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.3 A nontrivial example . . . . . . . . . . . . . . . . . . . . . . . . . 17
4 Advanced matrix computations 20
4.1 Eigenvalues and other numerical linear algebra computations . . 20
4.2 Sparse matrix computations . . . . . . . . . . . . . . . . . . . . . 22
4.2.1 Creating a sparse matrix . . . . . . . . . . . . . . . . . . . 22
5 Advanced Graphics 24
5.1 Putting several graphs in one window . . . . . . . . . . . . . . . 24
5.2 3D plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
5.3 Parametric plots . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
6 Solving nonlinear problems in Matlab 28
7 Eciency in Matlab 29
Department of Mathematical Sciences, Michigan Technological University
1
8 Advanced data types in Matlab 30
8.1 Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
8.2 Cell arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
8.3 Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1 Introduction
Matlab (Matrix laboratory) is an interactive software system for numerical
computations and graphics. As the name suggests, Matlab is especially de-
signed for matrix computations: solving systems of linear equations, computing
eigenvalues and eigenvectors, factoring matrices, and so forth. In addition, it
has a variety of graphical capabilities, and can be extended through programs
written in its own programming language. Many such programs come with the
system; a number of these extend Matlab's capabilities to nonlinear problems,
such as the solution of initial value problems for ordinary dierential equations.
Matlab is designed to solve problems numerically, that is, in nite-precision
arithmetic. Therefore it produces approximate rather than exact solutions,
and should not be confused with a symbolic computation system (SCS) such
as Mathematica or Maple. It should be understood that this does not make
Matlab better or worse than an SCS; it is a tool designed for dierent tasks and
is therefore not directly comparable.
In the following sections, I give an introduction to some of the most use-
ful features of Matlab. I include plenty of examples; the best way to learn
to use Matlab is to read this while running Matlab, trying the examples and
experimenting.
2
types (for example, a one-dimensional array whose rst entry is a scalar, second
entry a string, third entry a vector). I mostly discuss the basic features using
n-dimensional arrays, but I brie
y discuss the other data types later in the
paper.
The following commands show how to enter numbers, vectors and matrices,
and assign them to variables (>> is the Matlab prompt on my computer; it may
be dierent with dierent computers or dierent versions of Matlab. I am using
version 5.2.0.3084. On my Unix workstation, I start Matlab by typing matlab
at the Unix prompt.):
>> a = 2
a =
2
>> x = [1;2;3]
x =
1
2
3
>> A = [1 2 3;4 5 6;7 8 0]
A =
1 2 3
4 5 6
7 8 0
Notice that the rows of a matrix are separated by semicolons, while the entries
on a row are separated by spaces (or commas).
A useful command is \whos", which displays the names of all dened vari-
ables and their types:
>> whos
Name Size Bytes Class
Note that each of these three variables is an array; the \shape" of the array
determines its exact type. The scalar a is a 1 1 array, the vector x is a 3 1
array, and A is a 3 3 array (see the \size" entry for each variable).
One way to enter a n-dimensional array (n > 2) is to concatenate two or
more (n ; 1)-dimensional arrays using the cat command. For example, the
following command concatenates two 3 2 arrays to create a 3 2 2 array:
>> C = cat(3,[1,2;3,4;5,6],[7,8;9,10;11,12])
C(:,:,1) =
1 2
3
3 4
5 6
C(:,:,2) =
7 8
9 10
11 12
>> whos
Name Size Bytes Class
Note that the argument \3" in the cat command indicates that the concatena-
tion is to occur along the third dimension. If D and E were k m n arrays,
the command
>> cat(4,D,E)
This example shows how complex numbers are displayed in Matlab; it also shows
that the square root function is a built-in feature.
The result of the last calculation not assigned to a variable is automatically
assigned to the variable ans, which can then be used as any other variable in
subsequent computations. Here is an example:
>> 100^2-4*2*3
ans =
9976
>> sqrt(ans)
ans =
99.8799
>> (-100+ans)/4
ans =
-0.0300
The arithmetic operators work as expected for scalars. A built-in variable that
is often useful is :
4
>> pi
ans =
3.1416
Above I pointed out that the square root function is built-in; other common
scientic functions, such as sine, cosine, tangent, exponential, and logarithm are
also pre-dened. For example:
>> cos(.5)^2+sin(.5)^2
ans =
1
>> exp(1)
ans =
2.7183
>> log(ans)
ans =
1
>> help pi
PI 3.1415926535897....
PI = 4*atan(1) = imag(log(-1)) = 3.1415926535897....
A good place to start is with the command help help, which explains how
the help systems works, as well as some related commands. Typing help by
itself produces a list of topics for which help is available; looking at this list
we nd the entry \elfun|elementary math functions." Typing help elfun
produces a list of the math functions available. We see, for example, that the
inverse tangent function (or arctangent) is called atan:
>> pi-4*atan(1)
ans =
0
It is often useful, when entering a matrix, to suppress the display; this is done
by ending the line with a semicolon (see the rst example in the next section).
5
The command more can be used to cause Matlab to display only one page of
output at a time. Typing more on causes Matlab to pause between pages of
output from subsequent commands; as with the Unix \more" command, a space
character then advances the output by a page, a carriage return advances the
output one line, and the character \q" ends the output. Once the command
more on is issued, this feature is enabled until the command more off is given.
2.2 Graphs
The simplest graphs to create are plots of points in the cartesian plane. For
example:
>> x = [1;2;3;4;5];
>> y = [0;.25;3;1.5;2];
>> plot(x,y)
2.5
1.5
0.5
0
1 1.5 2 2.5 3 3.5 4 4.5 5
6
3
2.5
1.5
0.5
0
1 1.5 2 2.5 3 3.5 4 4.5 5
7
B 3x3 72 double array
C 3x2 48 double array
>> A+B
ans =
2 3 4
6 7 8
10 11 12
>> A+C
??? Error using ==> +
Matrix dimensions must agree.
8
Grand total is 10 elements using 80 bytes
>> C*D
??? Error using ==> *
No functional support for matrix inputs.
By the same token, the exponentiation operator ^ is only dened for square
2-dimensional arrays (matrices).
2.3.2 Solving matrix equations using matrix division
If A is a square, nonsingular matrix, then the solution of the equation Ax = b
is x = A;1 b. Matlab implements this operation with the backslash operator:
>> A = rand(3,3)
A =
0.2190 0.6793 0.5194
0.0470 0.9347 0.8310
0.6789 0.3835 0.0346
>> b = rand(3,1)
b =
0.0535
0.5297
0.6711
>> x = A\b
x =
-159.3380
314.8625
-344.5078
>> A*x-b
ans =
1.0e-13 *
-0.2602
-0.1732
-0.0322
(Notice the use of the built-in function rand, which creates a matrix with en-
tries from a uniform distribution on the interval (0; 1). See help rand for more
details.) Thus A\b is (mathematically) equivalent to multiplying b on the left by
A;1 (however, Matlab does not compute the inverse matrix; instead it solves the
linear system directly). When used with a nonsquare matrix, the backslash op-
erator solves the appropriate system in the least-squares sense; see help slash
for details. Of course, as with the other arithmetic operators, the matrices must
be compatible in size. The division operator is not dened for n-dimensional
arrays with n > 2.
9
2.3.3 Vectorized functions and operators; more on graphs
Matlab has many commands to create special matrices; the following command
creates a row vector whose components increase arithmetically:
>> t = 1:5
t =
1 2 3 4 5
The components can change by non-unit steps:
>> x = 0:.1:1
x =
Columns 1 through 7
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000
Columns 8 through 11
0.7000 0.8000 0.9000 1.0000
A negative step is also allowed. The command linspace has similar results;
it creates a vector with linearly spaced entries. Specically, linspace(a,b,n)
creates a vector of length n with entries a; a + (b ; a)=(n ; 1); a + 2(b ; a)=(n ;
1); : : : ; b:
>> linspace(0,1,11)
ans =
Columns 1 through 7
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000
Columns 8 through 11
0.7000 0.8000 0.9000 1.0000
There is a similar command logspace for creating vectors with logarithmically
spaced entries:
>> logspace(0,1,11)
ans =
Columns 1 through 7
1.0000 1.2589 1.5849 1.9953 2.5119 3.1623 3.9811
Columns 8 through 11
5.0119 6.3096 7.9433 10.0000
See help logspace for details.
A vector with linearly spaced entries can be regarded as dening a one-
dimensional grid, which is useful for graphing functions. To create a graph of
y = f (x) (or, to be precise, to graph points of the form (x; f (x)) and connect
them with line segments), one can create a grid in the vector x and then create
a vector y with the corresponding function values.
It is easy to create the needed vectors to graph a built-in function, since
Matlab functions are vectorized. This means that if a built-in function such as
sine is applied to a array, the eect is to create a new array of the same size
whose entries are the function values of the entries of the original array. For
example (see Figure 3):
10
>> x = (0:.1:2*pi);
>> y = sin(x);
>> plot(x,y)
0.8
0.6
0.4
0.2
−0.2
−0.4
−0.6
−0.8
−1
0 1 2 3 4 5 6 7
(the graph is not shown). Thus x.^2 squares each component of x, and x./z
divides each component of x by the corresponding component of z. Addition and
subtraction are performed component-wise by denition, so there are no \.+"
or \.-" operators. Note the dierence between A^2 and A.^2. The rst is only
dened if A is a square matrix, while the second is dened for any n-dimensional
array A.
11
>> A = [1 2;3 4]
A =
1 2
3 4
>> A'
ans =
1 3
2 4
>> B = A + i*.5*A
B =
1.0000 + 0.5000i 2.0000 + 1.0000i
3.0000 + 1.5000i 4.0000 + 2.0000i
>> B'
ans =
1.0000 - 0.5000i 3.0000 - 1.5000i
2.0000 - 1.0000i 4.0000 - 2.0000i
In the rare event that the transpose, rather than the conjugate transpose, is
needed, the \.'" operator is used:
>> B.'
ans =
1.0000 + 0.5000i 3.0000 + 1.5000i
2.0000 + 1.0000i 4.0000 + 2.0000i
(note that ' and .' are equivalent for matrices with real entries).
The following commands are frequently useful; more information can be
obtained from the on-line help system.
Creating matrices
zeros(m,n) creates an m n matrix of zeros;
ones(m,n) creates an m n matrix of ones;
eye(n) creates the n n identity matrix;
diag(v) (assuming v is an n-vector) creates an n n diagonal matrix with
v on the diagonal.
The commands zeros and ones can be given any number of integer arguments;
with k arguments, they each create a k-dimensional array of the indicated size.
formatting display and graphics
format
{ format short 3.1416
{ format short e 3.1416e+00
12
{ format long 3.14159265358979
{ format long e 3.141592653589793e+00
{ format compact suppresses extra line feeds (all of the output in this
paper is in compact format).
xlabel('string'), ylabel('string') label the horizontal and vertical
axes, respectively, in the current plot;
title('string') add a title to the current plot;
hold on freezes the current plot so that subsequent graphs will be dis-
played with the current;
hold off releases the current plot; the next plot will erase the current
before displaying;
subplot puts multiple plots in one graphics window.
Miscellaneous
max(x) returns the largest entry of x, if x is a vector; see help max for
the result when x is a k-dimensional array;
min(x) analogous to max;
abs(x) returns an array of the same size as x whose entries are the mag-
nitudes of the entries of x;
size(A) returns a 1 k vector with the number of rows, columns, etc. of
the k-dimensional array A;
length(x) returns the \length" of the array, i.e. max(size(A)).
3 Programming in Matlab
The capabilities of Matlab can be extended through programs written in its own
programming language. It provides the standard constructs, such as loops and
conditionals; these constructs can be used interactively to reduce the tedium of
repetitive tasks, or collected in programs stored in \m-les" (nothing more than
a text le with extension \.m"). I will rst discuss the programming mechanisms
and then explain how to write programs.
13
3.1 Conditionals and loops
Matlab has a standard if-elseif-else conditional; for example:
>> t = rand(1);
>> if t > 0.75
s = 0;
elseif t < 0.25
s = 1;
else
s = 1-2*(t-0.25);
end
>> s
s =
0
>> t
t =
0.7622
The logical operators in Matlab are <, >, <=, >=, == (logical equals), and
~= (not equal). These are binary operators which return the values 0 and 1 (for
scalar arguments):
>> 5>3
ans =
1
>> 5<3
ans =
0
>> 5==3
ans =
0
Thus the general form of the if statement is
if expr1
statements
elseif expr2
statements
.
.
.
else
statements
end
The rst block of statements following a nonzero expr executes.
Matlab provides two types of loops, a for-loop (comparable to a Fortran
do-loop or a C for-loop) and a while-loop. A for-loop repeats the statements in
the loop as the loop index takes on the values in a given row vector:
14
>> for i=[1,2,3,4]
disp(i^2)
end
1
4
9
16
(Note the use of the built-in function disp, which simply displays its argument.)
The loop, like an if-block, must be terminated by end. This loop would more
commonly be written as
>> for i=1:4
disp(i^2)
end
1
4
9
16
15
Then the sequence of commands
>> N=100;w=5;
>> plotsin
produces Figure 4.
0.8
0.6
0.4
0.2
−0.2
−0.4
−0.6
−0.8
−1
0 1 2 3 4 5 6 7
Figure 4: Eect of an m-le
As this example shows, the commands in the script can refer to the variables
already dened in Matlab, which are said to be in the global workspace (notice
the reference to N and w in plotsin.m). As I mentioned above, the commands in
the script are executed exactly as if they had been typed at the keyboard.
Much more powerful than scripts are functions, which allow the user to
create new Matlab commands. A function is dened in an m-le that begins
with a line of the following form:
function [output1,output2,...] = cmd name(input1,input2,...)
16
as the function executes are erased when the execution of the function ends,
unless they are passed back as outputs.
Here is a simple example of a function; it computes the function f (x) =
sin(x2 ). The following commands should be stored in the le fcn.m (the name
of the function within Matlab is the name of the m-le, without the extension):
function y = fcn(x)
y = sin(x.^2);
(Note that I used the vectorized operator .^ so that the function fcn is also
vectorized.) With this function dened, I can now use fcn just as the built-in
function sin:
>> x = (-pi:2*pi/100:pi)';
>> y = sin(x);
>> z = fcn(x);
>> plot(x,y,x,z)
>> grid
The graph is shown in Figure 5. Notice how plot can be used to graph two (or
more) functions together. The computer will display the curves with dierent
line types|dierent colors on a color monitor, or dierent styles (e.g. solid
versus dashed) on a black-and-white monitor. See help plot for more informa-
tion. Note also the use of the grid command to superimpose a cartesian grid
on the graph.
17
1
0.8
0.6
0.4
0.2
−0.2
−0.4
−0.6
−0.8
−1
−4 −3 −2 −1 0 1 2 3 4
and
>> feval('fcn',2)
ans =
-0.7568
are equivalent (notice that single quotes are used to delimit a string). A variable
can also be assigned the value of a string:
>> str = 'fcn'
str =
f
>> feval(str,2)
ans =
-0.7568
18
% c = bisect('fn',a,b,tol)
%
% This function locates a root of the function fn on the interval
% [a,b] to within a tolerance of tol. It is assumed that the function
% has opposite signs at a and b.
fa = feval(fn,a);
fb = feval(fn,b);
if fa*fb >= 0
error('The function must have opposite signs at a and b')
end
% The flag done is used to flag the unlikely event that we find
% the root exactly before the interval has been sufficiently reduced.
done = 0;
c = (a+b)/2;
% Main loop
fc = feval(fn,c);
end
19
Assuming that this le is named bisect.m, it can be run as follows:
>> x = bisect('fcn',1,2,1e-6)
x =
1.7725
>> sqrt(pi)-x
ans =
-4.1087e-07
Not only can new Matlab commands be created with m-les, but the help
system can be automatically extended. The help command will print the rst
comment block from an m-le:
>> help bisect
c = bisect('fn',a,b,tol)
(Something that may be confusing is the use of both fn and 'fn' in bisect.m.
I put quotes around fn in the comment block to remind the user that a string
must be passed. However, the variable fn is a string variable and does not need
quotes in any command line.)
Notice the use of the error function near the beginning of the program.
This function displays the string passed to it and exits the m-le.
At the risk of repeating myself, I want to re-emphasize a potentially trouble-
some point. In order to execute an m-le, Matlab must be able to nd it, which
means that it must be found in a directory in Matlab's path. The current work-
ing directory is always on the path; to display or change the path, use the path
command. To display or change the working directory, use the cd command.
As usual, help will provide more information.
20
eigenvalues. The equation AV = VD holds. If A is diagonalizable, then V is in-
vertible, while if A is symmetric, then V is orthogonal (V T V = I ).
Here is an example:
>> A = [1 3 2;4 5 6;7 8 9]
A =
1 3 2
4 5 6
7 8 9
>> eig(A)
ans =
15.9743
-0.4871 + 0.5711i
-0.4871 - 0.5711i
>> [V,D] = eig(A)
V =
-0.2155 0.0683 + 0.7215i 0.0683 - 0.7215i
-0.5277 -0.3613 - 0.0027i -0.3613 + 0.0027i
-0.8216 0.2851 - 0.5129i 0.2851 + 0.5129i
D =
15.9743 0 0
0 -0.4871 + 0.5711i 0
0 0 -0.4871 - 0.5711i
>> A*V-V*D
ans =
1.0e-14 *
-0.0888 0.0777 - 0.1998i 0.0777 + 0.1998i
0 -0.0583 + 0.0666i -0.0583 - 0.0666i
0 -0.0555 + 0.2387i -0.0555 - 0.2387i
There are many other matrix functions in Matlab, many of them related to
matrix factorizations. Some of the most useful are:
lu computes the LU factorization of a matrix;
chol computes the Cholesky factorization of a symmetric positive denite
matrix;
qr computes the QR factorization of a matrix;
svd computes the singular values or singular value decomposition of a
matrix;
cond, condest, rcond computes or estimates various condition num-
bers;
norm computes various matrix or vector norms;
21
4.2 Sparse matrix computations
Matlab has the ability to store and manipulate sparse matrices, which greatly
increases its usefulness for realistic problems. Creating a sparse matrix can be
rather dicult, but manipulating them is easy, since the same operators apply
to both sparse and dense matrices. In particular, the backslash operator works
with sparse matrices, so sparse systems can be solved in the same fashion as
dense systems. Some of the built-in functions apply to sparse matrices, but
others do not (for example, eig can be used on sparse symmetric matrix, but
not on a sparse nonsymmetric matrix).
4.2.1 Creating a sparse matrix
If a matrix A is stored in ordinary (dense) format, then the command S =
sparse(A) creates a copy of the matrix stored in sparse format. For example:
22
A =
(3,1) 4
(1,2) 1
(3,2) -1
(Of course, for this to be truly useful, the nonzeros would be added in a loop.)
Another version of the sparse command is S = sparse(I,J,S,m,n,maxnz).
This creates an m n sparse matrix with entry (I (k); J (k)) equal to S (k); k =
1; : : : ; length(S ). The optional argument maxnz causes Matlab to pre-allocate
storage for maxnz nonzero entries, which can increase eciency in the case when
more nonzeros will be added later to S.
There are still more versions of the sparse command. See help sparse for
details.
The most common type of sparse matrix is a banded matrix, that is, a matrix
with a few nonzero diagonals. Such a matrix can be created with the spdiags
command. Consider the following matrix:
>> A
A =
64 -16 0 -16 0 0 0 0 0
-16 64 -16 0 -16 0 0 0 0
0 -16 64 0 0 -16 0 0 0
-16 0 0 64 -16 0 -16 0 0
0 -16 0 -16 64 -16 0 -16 0
0 0 -16 0 -16 64 0 0 -16
0 0 0 -16 0 0 64 -16 0
0 0 0 0 -16 0 -16 64 -16
0 0 0 0 0 -16 0 -16 64
23
>> B = [
-16 -16 64 0 0
-16 -16 64 -16 0
-16 0 64 -16 0
-16 -16 64 0 -16
-16 -16 64 -16 -16
-16 0 64 -16 -16
0 -16 64 0 -16
0 -16 64 -16 -16
0 0 64 -16 -16
];
(notice the technique for entering the rows of a large matrix on several lines).
The spdiags command also needs the indices of the diagonals:
>> d = [-3,-1,0,1,3];
5 Advanced Graphics
Matlab can produce several dierent types of graphs: 2D curves, 3D surfaces,
contour plots of 3D surfaces, parametric curves in 2D and 3D. I will leave the
reader to nd most of the details from the online help system. Here I want to
show, by example, some of the possibilities. I will also explain the basics of
producing 3D plots.
24
0
10
0 2 4 6 8 10
nz = 33
>> t = (0:.1:2*pi)';
>> subplot(2,2,1)
>> plot(t,sin(t))
>> subplot(2,2,2)
>> plot(t,cos(t))
>> subplot(2,2,3)
>> plot(t,exp(t))
>> subplot(2,2,4)
>> plot(t,1./(1+t.^2))
5.2 3D plots
In order to create a graph of a surface in 3-space (or a contour plot of a surface),
it is necessary to evaluate the function on a regular rectangular grid. This can
be done using the meshgrid command. First, create 1D vectors describing the
grids in the x- and y-directions:
>> x = (0:2*pi/20:2*pi)';
>> y = (0:4*pi/40:4*pi)';
25
1 1
0.5 0.5
0 0
−0.5 −0.5
−1 −1
0 2 4 6 8 0 2 4 6 8
500 1
400 0.8
300 0.6
200 0.4
100 0.2
0 0
0 2 4 6 8 0 2 4 6 8
The eect of meshgrid is to create a vector X with the x-grid along each row, and
a vector Y with the y-grid along each column. Then, using vectorized functions
and/or operators, it is easy to evaluate a function z = f (x; y) of two variables
on the rectangular grid:
>> z = cos(X).*cos(2*Y);
Having created the matrix containing the samples of the function, the surface
can be graphed using either the mesh or the surf commands (see Figures 8 and
9, respectively):
26
>> mesh(x,y,z)
>> surf(x,y,z)
0.5
−0.5
−1
15
8
10
6
5 4
2
0 0
Use the help command to learn the additional options. These commands can
be very time-consuming if the grid is ne.
(note the use of the axis('square') command to make the circle appear round
instead of elliptic). See also the commands comet, comet3.
27
1
0.5
−0.5
−1
15
8
10
6
5 4
2
0 0
28
12
10
0
0 1 2 3 4 5 6
7 Eciency in Matlab
User-dened Matlab functions are interpreted, not compiled. This means roughly
that when an m-le is executed, each statement is read and then executed, rather
than the entire program being parsed and compiled into machine language. For
this reason, Matlab programs can be much slower than programs written in a
language such as Fortran or C.
In order to get the most out of Matlab, it is necessary to use built-in functions
and operators whenever possible (so that compiled rather than interpreted code
is executed). For example, the following two command sequences have the same
eect:
>> t = (0:.001:1)';
>> y=sin(t);
and
>> t = (0:.001:1)';
>> for i=1:length(t)
29
1
0.8
0.6
0.4
0.2
−0.2
−0.4
−0.6
−0.8
−1
−1 −0.5 0 0.5 1
y(i) = sin(t(i));
end
8.1 Structures
A structure is a data type which contains several values, possibly of dierent
types, referenced by name. The simplest way to create a structure is by simple
assignment. For example, consider the function
f (x) = (x1 ; 1)2 + x1 x2 :
30
The following m-le f.m computes the value, gradient, and Hessian of f at a
point x, and returns them in a structure:
function fx = f(x)
fx.Value = (x(1)-1)^2+x(1)*x(2);
fx.Gradient = [2*(x(1)-1)+x(2);x(1)];
fx.Hessian = [2 1;1 0];
>> fieldnames(fx)
ans =
'Value'
'Gradient'
'Hessian'
>> fieldnames(gx)
ans =
31
'Value'
'Gradient'
(Note the use of the command fieldnames, which lists the eld names of a
structure.)
Beyond simple assignment, there is a command struct for creating struc-
tures. For information on this and other commands for manipulating structures,
see help struct.
8.2 Cell arrays
A cell array is an array whose entries can be data of any type. The index
operator {} is used in place of () to indicate that an array is a cell array
instead of an ordinary array:
>> x = [2;1];
>> fx = f(x);
>> whos
Name Size Bytes Class
>> A{1}=x
A =
[2x1 double]
>> A{2}=fx
A =
[2x1 double] [1x1 struct]
>> whos
Name Size Bytes Class
Another way to create the same cell array is to place the entries inside of curly
braces:
>> B = {x,fx}
B =
[2x1 double] [1x1 struct]
For more information about cell arrays, see help cell.
32
8.3 Objects
Matlab 5 now supports the use of classes, which can be thought of structures
that contain both data and functions (class methods). (In contrast, a struct
contains only data.) One class can be derived from another class (the base
class), meaning that it inherits the properties|data and methods|of the base
class. Also, Matlab now supports overloading of functions. Through these
mechanisms, Matlab enables object-oriented design of programs.
For more information, see help class.
33