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

Numerical Analysis

Functions for Finite Differences

diff Difference between


successive elements of a vector
Numerical partial derivatives
of a vector
gradient Numerical partial derivatives
a matrix
del2 Discrete Laplacian of a
matrix
Functions for Fourier Analysis

fft Discrete Fourier transform


fft2 Two-dimensional discrete Fourier
transform
fftn N-dimensional discrete Fourier transform.
ifft Inverse discrete Fourier transform
ifft2 Two-dimensional inverse discrete Fourier
transform
ifftn N-dimensional inverse discrete Fourier
transform
abs Magnitude
angle Phase angle
Solving Linear Equations

Solution by Square System


Overdetermined System
Undetermined System
General situation involves a square coefficient
matrix A and a single right-hand side column
vector b.
e.g. Ax = b then solution: x = b\A
System is solved by ‘backslash’ operator
Overdetermined Equation

a
b(a ) c1 c2e

With a, b dataset fitting equation is predicted as


MATLAB finds C1 = 0.4763 and C2 = 0.3400
Undetermined Equation

More unknowns than equations


Solution is not unique
MATLAB finds a basic solution even it is not unique
Associated constraints can not be coupled to
MATLAB
Ordinary Differential Equations

Nonstiff solvers
ode23: an explicit Runge-Kutta (2,3) formula i.e.
Bogacki-Shampine pair
ode45: an explicit Runge-Kutta (4,5) formula i.e.
Dormand-Prince pair
ode113: Adams-Bashforth-Moulton PECE solver
Stiff solvers
ode15s, ode23s, ode23t and ode23tb
Generic Syntax for ODE Solver

>> [T,Y] = solver (‘Func’, tspan, y0);


'Func' String containing the name of the file
that contains the system of ODEs
tspan Vector specifying the interval of integration. For
a two-element vector tspan = [t0 tfinal], the
solver integrates from t0 to tfinal.
y0 Vector of initial conditions for the
problem.

Output:

T Column vector of time points


Y Solution array. Each row in Y corresponds to
the solution at a time returned in the
corresponding row of T
Numerical Integration

The area under a section of a function F(x) can be


evaluated by numerically integrating F(x), a process
known as quadrature. The in-built MATLAB
functions for 1D quadrature are:
quad - Adaptive Simpson’s Rule
quad8 - Adaptive Newton Cotes 8
panel rule
Numerical Integration - Example

>> Q = quad (‘sin’,0,2*pi)


>> Q = 0
Performing Double Integral

% function declaration
>> function integrnd_out = integrnd (x,y)
>> integrnd_out = x*sin(x) + y*cos(y);

% Double Integral Evaluation


>> x_min = pi;
>> x_max = 2*pi;
>> y_min = 0;
>> y_max = pi;
>>
>> intg_result = dblquad (‘integrnd’, x_min, x_max, y_min, y_max)
>> intg_result = -9.8698
Symbolic Mathematics
Symbolic Mathematics

The Symbolic Math Toolboxes include symbolic


computation into MATLAB’s numeric environment

Facilities Available with Symbolic Math Toolboxes


contain – Calculus, Linear Algebra, Simplification,
Solution of Equations, Variable-Precision
Arithmetic, Transforms and Special Applied
Functions
Demonstrations

Command Line Demonstrations are available


with Symbolic Math Toolboxes
Example: Differentiation

>> syms a x
>> fx = sin (a*x)
>> dfx = diff(fx)
>> dfx = cos (a*x)*a

% with respect to a
>> dfa = diff(fx, a)
>> dfa = cos (a*x)*x
Variables

The same guidelines that apply to MATLAB variables


at the command line also apply to variables in M-
files:
No need to type or declare variables used in M-files,
(with the possible exception of designating them as
global or persistent).
Variables

Before assigning one variable to another, you must


be sure that the variable on the right-hand side of
the assignment has a value.
Any operation that assigns a value to a variable
creates the variable, if needed, or overwrites its
current value, if it already exists.
Variables

MATLAB variable names must begin with a letter,


which may be followed by any combination of letters,
digits, and underscores.
MATLAB distinguishes between uppercase and
lowercase characters, so A and a are not the same
variable.
Avoid Using Function Names for Variables
Local Variables

Each MATLAB function has its own local variables.


These are separate from those of other functions,
and from those of the base workspace.
Local Variables

• Variables defined in a function do not


remain in memory from one function call
to the next,

unless they are defined as global or


persistent.
Local Variables

• Scripts, on the other hand, do not have a


separate workspace. They store their
variables in a workspace that is shared
with the caller of the script. When called
from the command line, they share the
base workspace. When called from a
function, they share that function's
workspace.
Global Variables
If several functions all declare a particular name as
global, then they all share a single copy of that
variable.

Any assignment to that variable, in any function, is


available to all the other functions declaring it global.
Global Variables
Creating Global Variables
Each function that uses a global variable must first
declare the variable as global.
You would declare global variable MAXLEN as
follows:
global MAXLEN
To access the variable from the MATLAB command
line, you must declare it as global at the command
line.
Global Variables
• Suppose, for example, you want to
study the effect coefficients on a
equation. Create an M-file,
myfunction.m.

function yp = myfunction(y)
%The function you want to check.
global ALPHA
yp = [y-ALPHA*y];
Global Variables
Then in the command prompt
enter the statements

global ALPHA
ALPHA = 0.01
y=myfunction(1:10);

The global statement make the


values assigned to ALPHA at the
command prompt available
inside the function defined by
myfunction.m. They can be
modified interactively and new
solutions obtained without
editing any files.
Persistent Variables

Characteristics of persistent variables are:


1. You can only use them in functions.
2. Other functions are not allowed access to
them.
3. MATLAB does not clear them from
memory when the function exits, so their
value is retained from one function call
to the next.
Persistent Variables

You must declare persistent variables as persistent


before you can use them in a function. It is usually
best to put persistent declarations toward the
beginning of the function. You would declare
persistent variable X as follows:
persistent X
Special Values

• ans: Most recent answer (variable). If


you do not assign an output variable
to an expression, MATLAB
automatically stores the result in ans.

• pi: 3.1415926535897...
Operators

The MATLAB operators fall into


three categories:

1. Arithmetic operators - perform


numeric computations
2. Relational operators - compare
operands quantitatively
3. Logical operators - use the logical
operators AND, OR
Arithmetic Operators

Operator Description

+ Addition

- Subtraction

.* Multiplication

./ Right division

.\ Left division

+ Unary plus
Arithmetic Operators

Operator Description
- Unary minus
: Colon operator
.^ Power
.' Transpose
' Complex conjugate transpose
* Matrix multiplication
/ Matrix right division
\ Matrix left division
^ Matrix power
Arithmetic Operators
/ Slash or matrix right
division.
B/A is roughly the same
as B*inv(A). More
precisely, B/A = (A'\B')'.

./ Array right division.


A./B is the matrix with
elements A(i,j)/B(i,j). A
and B must have the
same size, unless one of
them is a scalar.
Arithmetic Operators

\ Backslash or matrix left


division.
If A is a square matrix,
A\B is inv(A)*B.
.\ Array left division.
A.\B is the matrix with
elements B(i,j)/A(i,j).
A and B must have the
same size, unless one
of them is a scalar.
Relational Operators

Operator Description

< Less than

<= Less than or


equal to
> Greater than
Relational Operators

Operator Description

>= Greater than or


equal to
== Equal to

~= Not equal to
Logical Operators

MATLAB offers three types of logical operator and


functions.
• Element-wise - operate on corresponding
elements of logical arrays.
• Bit-wise - operate on corresponding bits of
integer values or arrays.
• Short-circuit - operate on scalar, logical
expressions.
Element-Wise Operators and Functions

Perform element-
wise logical
operations on their
inputs to produce a
like-sized output
array.
Element-Wise Operators and Functions

A and b must
have equal
dimensions,
with each
dimension
being the
same size.
Short-Circuit Operators

Perform AND and OR operations on


logical expressions containing scalar
values.
They are short-circuit operators in
that they only evaluate their second
operand when the result is not fully
determined by the first operand.
Short-Circuit Operators
Operator Description

&& Returns true (1) if both


inputs evaluate to true,
and false (0) if they do not.

|| Returns true (1) if either


input, or both, evaluate to
true, and false (0) if they
do not.
Short-Circuit Operators
Example:
if ((A==10)&&(B==20))
…..
end

if ((A==10)||(B==20))
…..
end
Flow Control

if, else and elseif, executes a group of


statements based on some logical condition.
switch, case and otherwise, executes different
groups of statements depending on the value
of some logical condition.
while executes a group of statements an
indefinite number of times, based on some
logical condition.
Flow Control

for executes a group of statements a fixed number


of times.
continue passes control to the next iteration of a
for or while loop, skipping any remaining
statements in the body of the loop.
break terminates execution of a for or while loop.
return causes execution to return to the invoking
function.
All flow constructs use end to indicate the end of the flow
control block.
Flow Control
Flow Control
Flow Control

Unlike the C language switch construct, the MATLAB switch


does not "fall through." That is, if the first case statement is
true, other case statements do not execute. Therefore, break
statements are not used.
Flow Control

switch can
handle
multiple
conditions in a
single case
statement by
enclosing the
case
expression in a
cell array.
Flow Control

The while loop executes a statement or group of statements


repeatedly as long as the controlling expression is true (1).
while expression
statements
end

Infinite loop
Exit a while loop at any time using the break statement.
Flow Control

The for loop executes a statement or group of statements a


predetermined number of times.
for index = indexstart:increment:indexend
statements
end
default increment is 1.You can specify any increment, including
a negative one.
x=[1,2,3,8,4];
for i = 2:6
x(i) = 2*x(i-1);
end
You can nest multiple for loops.
x=[1,2,3,8,4;4 9 7 10 15];
m=length(x(:,1));
n=length(x(1,:));
for i = 1:m
for j = 1:n
A(i,j) = 1/(i + j - 1);
end
end
Vectorizing Loops

MATLAB is designed for vector and matrix operations.


You can often speed up your M-file code by using vectorizing
algorithms that take advantage of this design.
Vectorization means converting for and while loops to
equivalent vector or matrix operations.
Compute the sine of 1001 values ranging from 0 to 10.
tic
i = 0;
for t = 0:.001:10
i = i+1;
y(i) = sin(t);
end
toc; t=toc
A vectorized version of the same code is:
tic
t = 0:.001:10;
y = sin(t);
toc
File Handling
•The most commonly used, high-level,
file I/O functions in MATLAB are save
and load.

save
•Saves workspace variables on disk.
•As an alternative to the save function,
select Save Workspace As from the File
menu in the MATLAB desktop, or use the
Workspace browser.
File Handling

Syntax
save
save filename
save filename var1 var2 ...
save('filename', ...)
Description
save by itself, stores all workspace variables in a
binary format in the current directory in a file
named matlab.mat. Retrieve the data with load.
File Handling

Load workspace variables from disk


Syntax
•load
•load filename
•load filename X Y Z
File Handling

Description
load - loads all the variables from the MAT-file matlab.mat,
if it exists, and returns an error if it doesn't exist.
load filename X Y Z ... loads just the specified variables
from the MAT-file. The wildcard '*' loads variables that
match a pattern (MAT-file only).
File Handling

Use the functional form of load, such as


load('filename'), when the file name is stored in a
string, when an output argument is requested, or if
filename contains spaces. To specify a command line
option with this functional form, specify the option
as a string argument, including the hyphen.
For example, load('myfile.dat‘,’-mat’)
File Handling

Read an ASCII delimited file into a matrix Graphical


Interface
As an alternative to dlmread, use the Import Wizard.
To activate the Import Wizard, select Import data
from the File menu.
Syntax
M = dlmread(filename,delimiter)
M = dlmread(filename,delimiter,R,C)
M = dlmread(filename,delimiter,range)
File Handling

Description
M = dlmread(filename,delimiter) reads numeric data from
the ASCII delimited file filename, using the specified
delimiter.
default delimiter - comma (,)
'\t‘ - tab
M = dlmread(filename,delimiter,R,C) reads numeric data
from the ASCII delimited file filename, using the specified
delimiter.
The values R and C specify the row and column where the
upper-left corner of the data lies in the file. R and C are zero
based so that R=0, C=0 specifies the first value in the file,
which is the upper left corner.
File Handling

M = dlmread(filename,delimiter,range) reads the


range specified by range = [R1 C1 R2 C2] where
(R1,C1) is the upper-left corner of the data to be
read and (R2,C2) is the lower-right corner.
Remarks
dlmread fills empty delimited fields with zero. Data
files having lines that end with a non-space
delimiter, such as a semi-colon, produce a result
that has an additional last column of zeros.
File Handling

Write a matrix to an ASCII delimited file Syntax


dlmwrite(filename,M,delimiter)
dlmwrite(filename,M,delimiter,R,C)
Description
dlmwrite(filename,M,delimiter) writes matrix M into an
ASCII-format file, using delimiter to separate matrix
elements.
default delimiter - comma (,)
'\t' – tab delimiter

You might also like