Numerical Methods in Engineering With MATLAB - 2005 (2) - 10-36 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

1 Introduction to MATLAB

1.1 General Information


Quick Overview
R
This chapter is not intended to be a comprehensive manual of MATLAB . Our sole
aim is to provide sufficient information to give you a good start. If you are familiar
with another computer language, and we assume that you are, it is not difficult to pick
up the rest as you go.
MATLAB is a high-level computer language for scientific computing and data vi-
sualization built around an interactive programming environment. It is becoming the
premiere platform for scientific computing at educational institutions and research
establishments. The great advantage of an interactive system is that programs can be
tested and debugged quickly, allowing the user to concentrate more on the principles
behind the program and less on programming itself. Since there is no need to com-
pile, link and execute after each correction, MATLAB programs can be developed in
much shorter time than equivalent FORTRAN or C programs. On the negative side,
MATLAB does not produce stand-alone applications—the programs can be run only
on computers that have MATLAB installed.
MATLAB has other advantages over mainstream languages that contribute to
rapid program development:

r 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.
r There is extensive graphics support that allows the results of computations to be
plotted with a few statements.
r All numerical objects are treated as double-precision arrays. Thus there is no need
to declare data types and carry out type conversions.

1
2 Introduction to MATLAB

The syntax of MATLAB resembles that of FORTRAN. To get an idea of the similari-
ties, let us compare the codes written in the two languages for solution of simultaneous
equations Ax = b by Gauss elimination. 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 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
3 1.1 General Information

if A(i,k) ˜= 0
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
end
end
%--------------Back substitution phase-----------
for k = n:-1:1
b(k) = (b(k) - A(k,k+1:n)*b(k+1:n))/A(k,k);
end

Simultaneous equations can also be solved in MATLAB with the simple command
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:

>> A = [2 1 0; -1 2 2; 0 1 4]; % Input 3 x 3 matrix


>> b = [1; 2; 3]; % Input column vector
>> soln = A\b % Solve A*x = b by left division
soln =
0.2500
0.5000
0.6250

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
4 Introduction to MATLAB

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

1.2 Data Types and Variables


Data Types
The most commonly used MATLAB data types, or classes, are double, char and
logical, all of which are considered by MATLAB as arrays. Numerical objects
belong to the class double, which represents double-precision arrays; a scalar is
treated as a 1 × 1 array. The elements of a char type array are strings (sequences
of characters), whereas a logical type array element may contain only 1 (true) or 0
(false).
Another important class is function handle, which is unique to MATLAB. It
contains information required to find and execute a function. The name of a function
handle consists of the character @, followed by the name of the function; e.g., @sin.
Function handles are used as input arguments in function calls. For example, suppose
that we have a MATLAB function plot(func,x1,x2) that plots any user-specified
function func from x1 to x2. The function call to plot sin x from 0 to π would be
plot(@sin,0,pi).
There are other data types, but we seldom come across them in this text. Additional
classes can be defined by the user. The class of an object can be displayed with the
class command. For example,

>> x = 1 + 3i % Complex number


>> class(x)
ans =
double
5 1.2 Data Types and Variables

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 declared
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 important
of which are

ans Default name for results


eps Smallest number for which 1 + eps > 1

inf Infinity
NaN Not a number

i or j −1
pi π
realmin Smallest usable positive number
realmax Largest usable positive number

Here are a few of examples:

>> warning off % Suppresses print of warning messages


>> 5/0
ans =
Inf

>> 0/0
6 Introduction to MATLAB

ans =
NaN

>> 5*NaN % Most operations with NaN result in NaN


ans =
NaN

>> NaN == NaN % Different NaN’s are not equal!


ans =
0

>> eps
ans =
2.2204e-016

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 semi-
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,
7 1.2 Data Types and Variables

>> b = [1 2 3] % Row vector


b =
1 2 3

>> b = [1; 2; 3] % Column vector


b =
1
2
3

>> b = [1 2 3]’ % Transpose of row vector


b =
1
2
3

The single quote (’) is the transpose operator in MATLAB; thus b’ is the transpose
of b.
The elements of a matrix, such as
⎡ ⎤
A11 A12 A13
⎢ ⎥
A = ⎣ A21 A22 A23 ⎦
A31 A32 A33

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
notation. Here is an illustration:

>> A = [8 1 6; 3 5 7; 4 9 2]
A =
8 1 6
3 5 7
4 9 2

>> A(2,3) % Element in row 2, column 3


ans =
7

>> A(:,2) % Second column


8 Introduction to MATLAB

ans =
1
5
9

>> A(2:3,2:3) % The 2 x 2 submatrix in lower right corner


ans =
5 7
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
their contents between braces {}. For example, a cell array c consisting of three cells
can be created by

>> c = { [1 2 3], ’one two three’, 6 + 7i}


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

Braces are also used to extract the contents of the cells:

>> c{ 1} % First cell


ans =
1 2 3
9 1.3 Operators

>> c{ 1} (2) % Second element of first cell


ans =
2
>> c{ 2} % Second cell
ans =
one two three

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 concatenated
with the function strcat, whereas a colon operator (:) is used to extract a portion of
the string. For example,

>> s1 = ’Press return to exit’; % Create a string


>> s2 = ’ the program’; % Create another string
>> s3 = strcat(s1,s2) % Concatenate s1 and s2
s3 =
Press return to exit the program
>> s4 = s1(1:12) % Extract chars. 1-12 of s1
s4 =
Press return

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.

>> A = [1 2 3; 4 5 6]; B = [7 8 9; 0 1 2];

>> A + B % Matrix addition


10 Introduction to MATLAB

ans =
8 10 12
4 6 8

>> A*B’ % Matrix multiplication


ans =
50 8
122 17

>> A*B % Matrix multiplication fails


??? Error using ==> * % due to incompatible dimensions
Inner matrix dimensions must agree.

There are two division operators in MATLAB:

/ 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

For example, the computation Ci j = Ai j Bi j can be accomplished with

>> A = [1 2 3; 4 5 6]; B = [7 8 9; 0 1 2];


>> C = A.*B
C =
7 16 27
0 5 12
11 1.3 Operators

Comparison Operators
The comparison (relational) operators return 1 for true and 0 for false. These operators
are

< Less than


> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
˜= Not equal to

The comparison operators always act element-wise on matrices; hence they result in
a matrix of logical type. For example,

>> A = [1 2 3; 4 5 6]; B = [7 8 9; 0 1 2];


>> A > B
ans =
0 0 0
1 1 1

Logical Operators
The logical operators in MATLAB are

& AND
| OR
˜ NOT

They are used to build compound relational expressions, an example of which is


shown below.

>> A = [1 2 3; 4 5 6]; B = [7 8 9; 0 1 2];


>> (A > B) | (B > 5)
ans =
1 1 1
1 1 1
12 Introduction to MATLAB

1.4 Flow Control


Conditionals
if, else, elseif
The if construct

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

which work in the same manner. The else clause

..
.
else
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 below illustrates the use of the
conditionals.

function sgn = signum(a)


if a > 0
sgn = 1;
elseif a < 0
sgn = -1;
else
13 1.4 Flow Control

sgn = 0;
end

>> signum (-1.5)


ans =
-1

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 statements
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
14 Introduction to MATLAB

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 principal
to grow to $10,000 at 6% annual interest.

>> p = 1000; years = 0;


>> while p < 10000
years = years + 1;
p = p*(1 + 0.06);
end
>> years
years =
40

for
The for loop requires a target and a sequence over which the target loops. The form
of the construct is

for target = sequence


block
end

For example, to compute cos x from x = 0 to π /2 at increments of π /10 we could


use

>> for n = 0:5 % n loops over the sequence 0 1 2 3 4 5


y(n+1) = cos(n*pi/10);
end
>> y
y =
1.0000 0.9511 0.8090 0.5878 0.3090 0.0000
15 1.4 Flow Control

Loops should be avoided whenever possible in favor of vectorized expressions,


which execute much faster. A vectorized solution to the last computation would be

>> n = 0:5;
>> y = cos(n*pi/10)
y =
1.0000 0.9511 0.8090 0.5878 0.3090 0.0000

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 fol-
lowing example the function buildvec constructs a row vector of arbitrary length
by prompting for its elements. The process is terminated when an empty element is
encountered.

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 that strips all the blanks from the string s1:

function s2 = strip(s1)
s2 = ’’; % Create an empty string
for i = 1:length(s1)
16 Introduction to MATLAB

if s1(i) == ’ ’
continue
else
s2 = strcat(s2,s1(i)); % Concatenation
end
end

>> s2 = strip(’This is too bad’)


s2 =
Thisistoobad

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 ex-
ample 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
iterations 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
statement. 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 a matrix and
aborts the program if the dimensions are not equal.
17 1.5 Functions

[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

function [output args] = function name(input arguments)

The input and output arguments must be separated by commas. The number of
arguments may be zero. If there is only one output argument, the enclosing brackets
may be omitted.
To make the function accessible to other programs units, it must be saved under
the file name function name.m. This file may contain other functions, called subfunc-
tions. The subfunctions can be called only by the primary function function name or
other subfunctions in the file; they are not accessible to other program units.

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 exam-
ple 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.

function [x,numIter] = solve(x,epsilon)


if nargin == 1 % Specify default value if
epsilon = 1.0e-6; % second input argument is
end % omitted in function call
for numIter = 1:100
dx = -(sin(x) - 0.5*x)/(cos(x) - 0.5);
x = x + dx;
if abs(dx) < epsilon % Converged; return to
return % calling program
end
18 Introduction to MATLAB

end
error(’Too many iterations’)

>> x = solve(2) % numIter not printed


x =
1.8955

>> [x,numIter] = solve(2) % numIter is printed


x =
1.8955
numIter =
4

>> format long


>> x = solve(2,1.0e-12) % Solving with extra precision
x =
1.89549426703398
>>

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 [x,numIter] = solve(x,epsilon)


if nargin == 1; epsilon = 1.0e-6; end
for numIter = 1:30
dx = myfunc(x);
x = x + dx;
if abs(dx) < epsilon; return; end
end
error(’Too many iterations’)

function y = myfunc(x)
y = -(sin(x) - 0.5*x)/(cos(x) - 0.5);

>> x = solve(2)
x =
1.8955
19 1.5 Functions

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

function [x,numIter] = solve(func,x,epsilon)


if nargin == 2; epsilon = 1.0e-6; end
for numIter = 1:30
dx = feval(func,x); % feval is a MATLAB function for
x = x + dx; % evaluating a passed function
if abs(dx) < epsilon; return; end
end
error(’Too many iterations’)

>> x = solve(@myfunc,2) % @myfunc is the function handle


x =
1.8955

The call solve(@myfunc,2)creates a function handle to myfunc and passes it


to solve as an argument. Hence the variable func in solve contains the handle
to myfunc. A function passed to another function by its handle is evaluated by the
MATLAB function

feval(function handle, arguments)

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.

In-Line Functions
If the function is not overly complicated, it can also be represented as an inline
object:

f unction name = inline(’expression ’,’var1 ’,’var2 ’,. . . )

where expression specifies the function and var1, var2, . . . are the names of the inde-
pendent variables. Here is an example:
>> myfunc = inline (’xˆ2 + yˆ2’,’x’,’y’);
>> myfunc (3,5)
ans =
34
20 Introduction to MATLAB

The advantage of an in-line function is that it can be embedded in the body of


the code; it does not have to reside in an M-file.

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

>> s = input(’Enter string: ’)


Enter string: ’Black sheep’
s =
Black sheep

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:

format long switches to 16-digit display


format short switches to 5-digit display

To print formatted output, use the fprintf function:

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
21 1.7 Array Manipulation

%w.df Floating point notation


%w.de Exponential notation
\n Newline character

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 formatted
table of sin x vs. 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

1.7 Array Manipulation


Creating Arrays
We learned before that an array can be created by typing its elements between brackets:

>> x = [0 0.25 0.5 0.75 1]


x =
0 0.2500 0.5000 0.7500 1.0000

Colon Operator
Arrays with equally spaced elements can also be constructed with the colon operator.

x = first elem:increment :last elem

For example,

>> x = 0:0.25:1
x =
0 0.2500 0.5000 0.7500 1.0000
22 Introduction to MATLAB

linspace
Another means of creating an array with equally spaced elements is the linspace
function. The statement

x = linspace(xfirst ,xlast ,n)

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

x = logspace(zfirst ,zlast ,n)

creates n logarithmically spaced elements starting with x = 10z f irst


and ending with
x = 10z last . 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 zeroes. When the fun-
ction is called with a single argument, e.g., zeros(n), a n × n matrix is created.

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.
23 1.7 Array Manipulation

eye
The function eye

X = eye(n)

creates an n × n identity matrix.

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 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 a 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:
24 Introduction to MATLAB

>> 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.
25 1.8 Writing and Running Programs

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.

1.8 Writing and Running Programs

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 interactive
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 function.
One can also create the P-code of a function and save it on disk by issuing the command

pcode function name

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. Variables
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.
26 Introduction to MATLAB

Assistance on any MATLAB function is available by typing

help function name

in the command window.

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.

>> x = 0:0.2:pi; % Create x-array


>> y = sin(x); % Create y-array
>> plot(x,y,’k:o’) % Plot x-y points with specified color
% and symbol (’k’ = black, ’o’ = circles)
>> hold on % Allow overwriting of current plot
>> z = cos(x); % Create z-array
>> plot(x,z,’k:x’) % Plot x-z points (’x’ = crosses)
>> grid on % Display coordinate grid
>> xlabel(’x’) % Display label for x-axis
>> ylabel(’y’) % Display label for y-axis
>> gtext(’sin x’) % Create mouse-movable text
>> gtext(’cos x’)
27 1.9 Plotting

A function stored in a M-file can be plotted with a single command, as shown


below.

function y = testfunc(x) % Stored function


y = (x.ˆ3).*sin(x) - 1./x;

>> fplot(@testfunc,[1 20]) % Plot from x = 1 to 20


>> grid on

The plots appearing in this book from here on were not produced by MATLAB.
We used the copy/paste operation to transfer the numerical data to a spreadsheet
and then let the spreadsheet create the plot. This resulted in plots more suited for
publication.

You might also like