05.0 PP 1 26 Introduction To MATLAB
05.0 PP 1 26 Introduction To MATLAB
1 Introduction to MATLAB
• MATLAB contains a large number of functions that access proven numerical li-
braries, such as LINPACK and EISPACK. This means that many common tasks
(e.g., solution of simultaneous equations) can be accomplished with a single
function call.
• There is extensive graphics support that allows the results of computations to be
plotted with a few statements.
• All numerical objects are treated as double-precision arrays. Thus there is no
need to declare data types and carry out type conversions.
• MATLAB programs are clean and easy to read; they lack the syntactic clutter of
some mainstream languages (e.g., C).
2 Introduction to MATLAB
The syntax of MATLAB resembles that of FORTRAN. To get an idea of the simi-
larities, let us compare the codes written in the two languages for solution of simul-
taneous equations Ax = b by Gauss elimination (do not worry about understanding
the inner workings of the programs). Here is the subroutine in FORTRAN 90:
subroutine gauss(A,b,n)
use prec_mod
implicit none
real(DP), dimension(:,:), intent(in out) :: A
real(DP), dimension(:), intent(in out) :: b
integer, intent(in) :: n
real(DP) :: lambda
integer :: i,k
! --------------Elimination phase--------------
do k = 1,n-1
do i = k+1,n
if(A(i,k) /= 0) then
lambda = A(i,k)/A(k,k)
A(i,k+1:n) = A(i,k+1:n) - lambda*A(k,k+1:n)
b(i) = b(i) - lambda*b(k)
end if
end do
end do
! ------------Back substitution phase----------
do k = n,1,-1
b(k) = (b(k) - sum(A(k,k+1:n)*b(k+1:n)))/A(k,k)
end do
return
end subroutine gauss
The statement use prec mod tells the compiler to load the module prec mod
(not shown here), which defines the word length DP for floating-point numbers. Also
note the use of array sections, such as a(k,k+1:n), a very useful feature that was not
available in previous versions of FORTRAN.
The equivalent MATLAB function is (MATLAB does not have subroutines):
function b = gauss(A,b)
n = length(b);
%-----------------Elimination phase-------------
for k = 1:n-1
for i = k+1:n
if A(i,k) ˜= 0
lambda = A(i,k)/A(k,k);
Simultaneous equations can also be solved in MATLAB with the simple com-
mand A\b (see below).
MATLAB can be operated in the interactive mode through its command window,
where each command is executed immediately upon its entry. In this mode MATLAB
acts like an electronic calculator. Here is an example of an interactive session for the
solution of simultaneous equations:
The symbol >> is MATLAB’s prompt for input. The percent sign (%) marks the
beginning of a comment. A semicolon (;) has two functions: it suppresses printout
of intermediate results and separates the rows of a matrix. Without a terminating
semicolon, the result of a command would be displayed. For example, omission of
the last semicolon in the line defining the matrix A would result in
>> A = [2 1 0; -1 2 2; 0 1 4]
A =
2 1 0
-1 2 2
0 1 4
Functions and programs can be created with the MATLAB editor/debugger and
saved with the .m extension (MATLAB calls them M-files). The file name of a saved
function should be identical to the name of the function. For example, if the function
for Gauss elimination listed above is saved as gauss.m, it can be called just like any
4 Introduction to MATLAB
MATLAB function:
>> A = [2 1 0; -1 2 2; 0 1 4];
>> b = [1; 2; 3];
>> soln = gauss(A,b)
soln =
0.2500
0.5000
0.6250
Variables
Variable names, which must start with a letter, are case sensitive. Hence xstart and
XStart represent two different variables. The length of the name is unlimited, but
only the first N characters are significant. To find N for your installation of MATLAB,
use the command namelengthmax:
>> namelengthmax
ans =
63
Variables that are defined within a MATLAB function are local in their scope.
They are not available to other parts of the program and do not remain in memory
after exiting the function (this applies to most programming languages). However,
variables can be shared between a function and the calling program if they are de-
clared global. For example, by placing the statement global X Y in a function as
well as the calling program, the variables X and Y are shared between the two program
units. The recommended practice is to use capital letters for global variables.
MATLAB contains several built-in constants and special variables, most impor-
tant of which are
>> 0/0
ans =
NaN
>> eps
ans =
2.2204e-016
6 Introduction to MATLAB
Arrays
Arrays can be created in several ways. One of them is to type the elements of the array
between brackets. The elements in each row must be separated by blanks or commas.
Here is an example of generating a 3 × 3 matrix:
>> A = [ 2 -1 0
-1 2 -1
0 -1 1]
A =
2 -1 0
-1 2 -1
0 -1 1
The elements can also be typed on a single line, separating the rows with colons:
>> A = [2 -1 0; -1 2 -1; 0 -1 1]
A =
2 -1 0
-1 2 -1
0 -1 1
Unlike most computer languages, MATLAB differentiates between row and col-
umn vectors (this peculiarity is a frequent source of programming and input errors).
For example,
The single quote (’) is the transpose operator in MATLAB; thus, b’ is the trans-
pose of b.
The elements of a matrix, such as
A 11 A 12 A 13
A = A 21 A 22 A 23
A 31 A 32 A 33
can be accessed with the statement A(i,j), where i and j are the row and column
numbers, respectively. A section of an array can be extracted by the use of colon no-
tation. Here is an illustration:
>> A = [8 1 6; 3 5 7; 4 9 2]
A =
8 1 6
3 5 7
4 9 2
Array elements can also be accessed with a single index. Thus A(i) extracts the
ithelement of A, counting the elements down the columns. For example, A(7) and
A(1,3) would extract the same element from a 3 × 3 matrix.
Cells
A cell array is a sequence of arbitrary objects. Cell arrays can be created by enclosing
its contents between braces {}. For example, a cell array c consisting of three cells
can be created by
8 Introduction to MATLAB
c =
[1x3 double] ’one two three’ [6.0000+ 7.0000i]
As seen above, the contents of some cells are not printed in order to save space.
If all contents are to be displayed, use the celldisp command:
>> celldisp(c)
c{1} =
1 2 3
c{2} =
one two three
c{3} =
6.0000 + 7.0000i
Strings
A string is a sequence of characters; it is treated by MATLAB as a character array.
Strings are created by enclosing the characters between single quotes. They are con-
catenated with the function strcat, whereas colon operator (:) is used to extract a
portion of the string. For example,
9 1.3 Operators
1.3 Operators
Arithmetic Operators
MATLAB supports the usual arithmetic operators
+ Addition
− Subtraction
∗ Multiplication
ˆ Exponentiation
When applied to matrices, they perform the familiar matrix operations, as illus-
trated below.
/ Right division
\ Left division
If a and b are scalars, the right division a/b results in a divided by b, whereas the left
division is equivalent to b/a. In the case where A and B are matrices, A/B returns the
solution of X*A = B and A\B yields the solution of A*X = B.
Often we need to apply the *, /, and ˆ operations to matrices in an element-
by-element fashion. This can be done by preceding the operator with a period (.) as
follows:
.* Element-wise multiplication
./ Element-wise division
.ˆ Element-wise exponentiation
10 Introduction to MATLAB
Comparison Operators
The comparison (relational) operators return 1 for true and 0 for false. These opera-
tors are
The comparison operators always act element-wise on matrices; hence, they result
in a matrix of logical type. For example,
Logical Operators
The logical operators in MATLAB are
& AND
| OR
˜ NOT
if condition
block
end
executes the block of statements if the condition is true. If the condition is false,
the block skipped. The if conditional can be followed by any number of elseif
constructs:
if condition
block
elseif condition
block
..
.
end
can be used to define the block of statements which are to be executed if none of the
if–elseif clauses are true. The function signum, which determines the sign of a
variable, illustrates the use of the conditionals:
function sgn = signum(a)
if a > 0
sgn = 1;
elseif a < 0
sgn = -1;
else
sgn = 0;
end
12 Introduction to MATLAB
switch
The switch construct is
switch expression
case value1
block
case value2
block
..
.
otherwise
block
end
Here the expression is evaluated and the control is passed to the case that matches
the value. For instance, if the value of expression is equal to value2, the block of state-
ments following case value2 is executed. If the value of expression does not match
any of the case values, the control passes to the optional otherwise block. Here is
an example:
function y = trig(func,x)
switch func
case ’sin’
y = sin(x);
case ’cos’
y = cos(x);
case ’tan’
y = tan(x);
otherwise
error(’No such function defined’)
end
>> trig(’tan’,pi/3)
ans =
1.7321
Loops
while
The while construct
while condition:
block
end
executes a block of statements if the condition is true. After execution of the block,
condition is evaluated again. If it is still true, the block is executed again. This process
is continued until the condition becomes false.
The following example computes the number of years it takes for a $1000 princi-
pal to grow to $10,000 at 6% annual interest.
for
The for loop requires a target and a sequence over which the target loops. The form
of the construct is
>> n = 0:5;
>> y = cos(n*pi/10)
y =
1.0000 0.9511 0.8090 0.5878 0.3090 0.0000
14 Introduction to MATLAB
break
Any loop can be terminated by the break statement. Upon encountering a break
statement, the control is passed to the first statement outside the loop. In the follow-
ing example, the function buildvec constructs a row vector of arbitrary length by
prompting for its elements. The process is terminated when the input is an empty
element.
function x = buildvec
for i = 1:1000
elem = input(’==> ’); % Prompts for input of element
if isempty(elem) % Check for empty element
break
end
x(i) = elem;
end
>> x = buildvec
==> 3
==> 5
==> 7
==> 2
==>
x =
3 5 7 2
continue
When the continue statement is encountered in a loop, the control is passed to
the next iteration without executing the statements in the current iteration. As an
illustration, consider the following function, which strips all the blanks from the
string s1:
function s2 = strip(s1)
s2 = ’’; % Create an empty string
for i = 1:length(s1)
if s1(i) == ’ ’
continue
else
s2 = strcat(s2,s1(i)); % Concatenation
end
end
15 1.5 Functions
return
A function normally returns to the calling program when it runs out of statements.
However, the function can be forced to exit with the return command. In the exam-
ple below, the function solve uses the Newton–Raphson method to find the zero of
f (x) = sin x − 0.5x. The input x (guess of the solution) is refined in successive iter-
ations using the formula x ← x + x, where x = −f (x)/f (x), until the change x
becomes sufficiently small. The procedure is then terminated with the return state-
ment. The for loop assures that the number of iterations does not exceed 30, which
should be more than enough for convergence.
function x = solve(x)
for numIter = 1:30
dx = -(sin(x) - 0.5*x)/(cos(x) - 0.5); % -f(x)/f’(x)
x = x + dx;
if abs(dx) < 1.0e-6 % Check for convergence
return
end
end
error(’Too many iterations’)
>> x = solve(2)
x =
1.8955
error
Execution of a program can be terminated and a message displayed with the error
function
error(’message’)
For example, the following program lines determine the dimensions of matrix and
aborts the program if the dimensions are not equal.
[m,n] = size(A); % m = no. of rows; n = no. of cols.
if m ˜= n
error(’Matrix must be square’)
end
1.5 Functions
Function Definition
The body of a function must be preceded by the function definition line
16 Introduction to MATLAB
The input and output arguments must be separated by commas. The number of ar-
guments may be zero. If there is only one output argument, the enclosing brackets
may be omitted.
To make the function accessible to other program units, it must be saved under
the file name function name.m.
Subfunctions
A function M-file may contain other functions in addition to the primary function.
These so-called subfunctions can be called only by the primary function or other
subfunctions in the file; they are not accessible to other program units. Otherwise,
subfunctions behave as regular functions. In particular, the scope of variables de-
fined within a subfunction is local; that is, these variables are not visible to the calling
function. The primary function must be the first function in the M-file.
Nested Functions
A nested function is a function that is defined within another function. A nested func-
tion can be called only by the function in which it is embedded. Nested functions
differ from subfunctions in the scope of the variables: a nested subfunction has ac-
cess to all the variables in the calling function and vice versa.
Normally, a function does not require a terminating end statement. This is not
true for nested functions, where the end statement is mandatory for all functions
residing in the M-file.
Calling Functions
A function may be called with fewer arguments than appear in the function defini-
tion. The number of input and output arguments used in the function call can be
determined by the functions nargin and nargout, respectively. The following ex-
ample shows a modified version of the function solve that involves two input and
two output arguments. The error tolerance epsilon is an optional input that may
be used to override the default value 1.0e-6. The output argument numIter, which
contains the number of iterations, may also be omitted from the function call.
17 1.5 Functions
Evaluating Functions
Let us consider a slightly different version of the function solve shown below. The
expression for dx, namely, x = −f (x)/f (x), is now coded in the function myfunc,
so that solve contains a call to myfunc. This will work fine, provided that myfunc is
stored under the file name myfunc.m so that MATLAB can find it.
function y = myfunc(x)
y = -(sin(x) - 0.5*x)/(cos(x) - 0.5);
>> x = solve(2)
x =
1.8955
In the above version of solve the function returning dx is stuck with the name
myfunc. If myfunc is replaced with another function name, solve will not work
18 Introduction to MATLAB
unless the corresponding change is made in its code. In general, it is not a good
idea to alter computer code that has been tested and debugged; all data should be
communicated to a function through its arguments. MATLAB makes this possible by
passing the function handle of myfunc to solve as an argument, as illustrated below.
It is now possible to use solve to find a zero of any f (x) by coding the function
x = −f (x)/f (x) and passing its handle to solve.
Anonymous Functions
If a function is not overly complicated, it can be represented as an anonymous func-
tion. The advantage of an anonymous function is that it is embedded in the program
code rather than residing in a separate M-file. An anonymous function is created with
the command
which returns the function handle of the function defined by expression. The input
arguments must be separated by commas. Being a function handle, an anonymous
function can be passed to another function as an input argument. The following
shows how the last example could be handled by creating the anonymous function
myfunc and passing it to solve.
19 1.6 Input/Output
x =
1.8955
x =
1.8955
Inline Functions
Another means of avoiding a function M-file is by creating an inline object from a
string expression of the function. This can be done by the command
Here expression describes the function and arg1, arg2, . . . are the input arguments. If
there is only one argument, it can be omitted. An inline object can also be passed to
a function as an input argument, as seen in the following example.
1.6 Input/Output
Reading Input
The MATLAB function for receiving user input is
value = input(’prompt ’)
It displays a prompt and then waits for input. If the input is an expression, it is evalu-
ated and returned in value. The following two samples illustrate the use of input:
>> a = input(’Enter expression: ’)
Enter expression: tan(0.15)
a =
0.1511
20 Introduction to MATLAB
Printing Output
As mentioned before, the result of a statement is printed if the statement does not end
with a semicolon. This is the easiest way of displaying results in MATLAB. Normally
MATLAB displays numerical results with about five digits, but this can be changed
with the format command:
fprintf(’format ’, list )
where format contains formatting specifications and list is the list of items to be
printed, separated by commas. Typically used formatting specifications are
where w is the width of the field and d is the number of digits after the decimal point.
Line break is forced by the newline character. The following example prints a format-
ted table of sin x versus x at intervals of 0.2:
>> x = 0:0.2:1;
>> for i = 1:length(x)
fprintf(’%4.1f %11.6f\n’,x(i),sin(x(i)))
end
0.0 0.000000
0.2 0.198669
0.4 0.389418
0.6 0.564642
0.8 0.717356
1.0 0.841471
Colon Operator
Arrays with equally spaced elements can also be constructed with the colon operator.
For example,
>> x = 0:0.25:1
x =
0 0.2500 0.5000 0.7500 1.0000
linspace
Another means of creating an array with equally spaced elements is the linspace
function. The statement
creates an array of n elements starting with xfirst and ending with xlast. Here is an
illustration:
>> x = linspace(0,1,5)
x =
0 0.2500 0.5000 0.7500 1.0000
logspace
The function logspace is the logarithmic counterpart of linspace. The call
creates n logarithmically spaced elements starting with x = 10zfir st and ending with
x = 10zlast . Here is an example:
>> x = logspace(0,1,5)
x =
1.0000 1.7783 3.1623 5.6234 10.0000
zeros
The function call
X = zeros(m,n)
returns a matrix of m rows and n columns that is filled with zeros. When the function
is called with a single argument, for example, zeros(n), an n × n matrix is created.
22 Introduction to MATLAB
ones
X = ones(m,n)
The function ones works in the manner as zeros, but fills the matrix with ones.
rand
X = rand(m,n)
This function returns a matrix filled with random numbers between 0 and 1.
eye
The function eye
X = eye(n)
Array Functions
There are numerous array functions in MATLAB that perform matrix operations and
other useful tasks. Here are a few basic functions:
length
The length n (number of elements) of a vector x can be determined with the function
length:
n = length(x)
size
If the function size is called with a single input argument:
[m,n] = size(X )
it determines the number of rows m and the number of columns n in the matrix X. If
called with two input arguments:
m = size(X ,dim)
it returns the length of X in the specified dimension (dim = 1 yields the number of
rows, and dim = 2 gives the number of columns).
reshape
The reshape function is used to rearrange the elements of a matrix. The call
Y = reshape(X ,m,n)
returns an m × n matrix the elements of which are taken from matrix X in the
column-wise order. The total number of elements in X must be equal to m × n. Here
is an example:
>> a = 1:2:11
a =
1 3 5 7 9 11
>> A = reshape(a,2,3)
A =
1 5 9
3 7 11
dot
a = dot(x,y )
This function returns the dot product of two vectors x and y which must be of the
same length.
prod
a = prod(x)
For a vector x, prod(x) returns the product of its elements. If x is a matrix, then a is
a row vector containing the products over each column. For example,
>> a = [1 2 3 4 5 6];
>> A = reshape(a,2,3)
A =
1 3 5
2 4 6
>> prod(a)
ans =
720
>> prod(A)
ans =
2 12 30
sum
a = sum(x)
This function is similar to prod, except that it returns the sum of the elements.
24 Introduction to MATLAB
cross
c = cross(a,b)
The function cross computes the cross product: c = a × b, where vectors a and b
must be of length 3.
MATLAB has two windows available for typing program lines: the command window
and the editor/debugger. The command window is always in the interactive mode, so
that any statement entered into the window is immediately processed. The interac-
tive mode is a good way to experiment with the language and try out programming
ideas.
MATLAB opens the editor window when a new M-file is created, or an existing
file is opened. The editor window is used to type and save programs (called script
files in MATLAB) and functions. One could also use a text editor to enter program
lines, but the MATLAB editor has MATLAB-specific features, such as color coding and
automatic indentation, that make work easier. Before a program or function can be
executed, it must be saved as a MATLAB M-file (recall that these files have the .m
extension). A program can be run by invoking the run command from the editor’s
debug menu.
When a function is called for the first time during a program run, it is compiled
into P-code (pseudo-code) to speed up execution in subsequent calls to the func-
tion. One can also create the P-code of a function and save it on disk by issuing the
command
MATLAB will then load the P-code (which has the .p extension) into the memory
rather than the text file.
The variables created during a MATLAB session are saved in the MATLAB
workspace until they are cleared. Listing of the saved variables can be displayed by
the command who. If greater detail about the variables is required, type whos. Vari-
ables can be cleared from the workspace with the command
clear a b . . .
which clears the variables a, b, . . .. If the list of variables is omitted, all variables are
cleared.
Assistance on any MATLAB function is available by typing
25 1.9 Plotting
1.9 Plotting
MATLAB has extensive plotting capabilities. Here we illustrate some basic commands
for two-dimensional plots. The example below plots sin x and cos x on the same plot.
% Plot example
x = 0:0.05*pi:2*pi; % Create x-array
y = sin(x); % Create y-array
plot(x,y,’k-o’) % Plot x-y points with specified color
% (’k’ = black) and symbol (’o’ = circle)
hold on % Allows overwriting of current plot
z = cos(x); % Create z-array
plot(x,z,’k-x’) % Plot x-z points (’x’ = cross)
grid on % Display coordinate grid
xlabel(’x’) % Display label for x-axis
gtext(’sin x’) % Create mouse-movable text (move cross-
gtext(’cos x’) % hairs to the desired location and
% press ’Enter’)
0.8
0.6
0.4
0.2
sin x
0
−0.2
−0.4
cos x
−0.6
−0.8
−1
0 1 2 3 4 5 6 7
x
26 Introduction to MATLAB
8000
6000
4000
2000
−2000
−4000
−6000
2 4 6 8 10 12 14 16 18 20