0% found this document useful (0 votes)
2 views

Lecture 2 - Modeling and Computing(2)_2

Uploaded by

m.m.m.essa22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 2 - Modeling and Computing(2)_2

Uploaded by

m.m.m.essa22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

GENG 603

Advanced Numerical Methods


Lecture 2
Modeling and Computing

© McGraw Hill LLC


MATLAB Fundamentals

© McGraw Hill LLC


Objectives
• Learning how real and complex numbers are assigned to variables.
• Learning how vectors and matrices are assigned values using simple
assignment, the colon operator (:), and the linspace and logspace
functions.
• Understanding the priority rules for constructing mathematical
expressions.
• Gaining a general understanding of built-in functions and how you can
learn more about them with MATLAB’s Help facilities.
• Learning how to use vectors to create a simple line plot based on an
equation.

© McGraw Hill LLC


The MATLAB Environment

MATLAB uses three primary windows-


• Command window - used to enter commands and data.
• Graphics window(s) - used to display plots and graphics.
• Edit window - used to create and edit M-files (programs).
Depending on your computer platform and the version of
MATLAB used, these windows may have different looks
and feels.

© McGraw Hill LLC


Calculator Mode

• The MATLAB command window can be used as a calculator


where you can type in commands line by line. Whenever a
calculation is performed, MATLAB will assign the result to
the built-in variable ans
• Example:
>> minus(55,16) % 55 minus 16 = 55 - 16
ans =
39

© McGraw Hill LLC


MATLAB Variables
• While using the ans variable may be useful for performing quick
calculations, its transient nature makes it less useful for programming.
• MATLAB allows you to assign values to variable names.
• This results in the storage of values to memory locations corresponding to the variable
name.
• MATLAB can store individual values as well as arrays;
• it can store numerical data and text (which is actually stored numerically as well).
• MATLAB requires that when you create a variable to initialize it;

© McGraw Hill LLC


Scalars, Part 1

• To assign a single value to a variable, simply type the


variable name, the = sign, and the value:
>> a = 4
a =
4

• Note that variable names must start with a letter, though they
can contain letters, numbers, and the underscore (_) symbol

© McGraw Hill LLC


Scalars, Part 2

• You can tell MATLAB not to report the result of a


calculation by appending the semi-colon (;) to the end of a
line.
• The calculation is still performed.
• You can ask MATLAB to report the value stored in a
variable by typing its name or using the disp command:
>> a % or disp(a)
a =
4
© McGraw Hill LLC
Scalars, Part 3
• You can use the complex variable i (or j) to represent the unit
imaginary number.
• You can tell MATLAB to report the values back with several
different formats using the format command (to know more use the
help format command).
• Note that the values are still stored the same way, though they are displayed
on the screen differently. Some examples are:
• short - Short fixed point format with 4 digits after the decimal point.
• long - Long scientific notation with 15 digits after the decimal point for double values and 7
digits after the decimal point for single values.
• shorteng - Engineering format with 4 digits after the decimal point and a power that is a
multiple of three.

© McGraw Hill LLC


Format Examples
>> format short; pi
ans =
3.1416
>> format long; pi
ans =
3.14159265358979
>> format shorteng; pi
ans =
3.1416e+000
>> pi*10000
ans =
31.4159e+003
Note - the format remains the same unless another format
command is issued.
© McGraw Hill LLC
Arrays, Vectors, and Matrices

• MATLAB can automatically handle rectangular arrays of


data.
• One-dimensional arrays are called vectors and
• Two-dimensional arrays are called matrices.
• Arrays are set off using square brackets [ and ] in MATLAB
• Entries within a row are separated by spaces or commas
• Rows are separated by semicolons

© McGraw Hill LLC


Array Examples
>> a = [1 2 3 4 5 ]
a =
1 2 3 4 5
>> b = [2;4;6;8;10]
b =
2
4
6
8
10
Note 1 - MATLAB does not display the brackets
Note 2 - if you are using a monospaced font, such as Courier, the displayed values should
line up properly
© McGraw Hill LLC
Matrices

• A 2-D array, or matrix, of data is entered row by row, with


spaces (or commas) separating entries within the row and
semicolons separating the rows:
>> A = [1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9

© McGraw Hill LLC


Useful Array Commands
• The transpose operator (apostrophe) can be used to flip an array over
its own diagonal.
• For example, if b is a row vector, b’ is a column vector.
• If b is complex b’ contains the complex conjugate of b.
• The command window will allow you to separate rows by hitting the
Enter key
• script files and functions will allow you to put rows on new lines as well.
• The who command will report back used variable names;
• whos will also give you the size, memory, and data types for the
arrays.

© McGraw Hill LLC


Accessing Array Entries: Part 1
• Individual entries within an array can be both read and set using either
the index of the location in the array or the row and column.
• The index value starts with 1 for the entry in the top left corner of an
array and increases down a column - the following shows the indices
for a 4 row, 3 column matrix:

1 5 9
2 6 10
3 7 11
4 8 12

© McGraw Hill LLC


Accessing Array Entries: Part 2
Assuming some matrix C:
C =[
2 4 9
3 3 16
3 0 8
10 13 17];
C(2) would report 3
C(4) would report 10
C(13) would report an error!
Entries can also be access using the row and column:
C(2,1) would report 3
C(3,2) would report 0
C(5,1) would report an error!
© McGraw Hill LLC
Array Creation - Built In

• There are several built-in functions to create arrays:


• zeros(r,c) will create an r row by c column matrix of zeros.
• zeros(n) will create an n by n matrix of zeros.
• ones(r,c) will create an r row by c column matrix of ones.
• ones(n) will create an n by n matrix one ones.

• help elmat has, among other things, a list of the


elementary matrices.

© McGraw Hill LLC


Array Creation - Colon Operator :
• The colon operator : is useful in several contexts.
• It can be used to create a linearly spaced array of points using the notation
start:diffval:limit
• where start is the first value in the array,
• diffval is the difference between successive values in the array, and
• limit is the boundary for the last value (though not necessarily the last value).

>>1:0.6:3
ans =
1.0000 1.6000 2.2000 2.8000

© McGraw Hill LLC


Colon Operator - Notes
If diffval is omitted, the default value is 1:
>>3:6
ans =
3 4 5 6
To create a decreasing series, diffval must be negative:
>> 5:-1.2:2
ans =
5.0000 3.8000 2.6000
If start+diffval>limit for an increasing series or start+diffval<limit for a
decreasing series, an empty matrix is returned:
>>5:2
ans =
Empty matrix: 1-by-0
To create a column, transpose the output of the colon operator (but not the limit value)
that is: (3:6)′ not 3:6′
© McGraw Hill LLC
Array Creation - linspace
• To create a row vector with a specific number of linearly spaced points between two
numbers, use the linspace command.
linspace(x1, x2, n) will create a linearly spaced array of n points between x1 and x2
>>linspace(0, 1, 6)
ans =
0 0.2000 0.4000 0.6000 0.8000 1.0000

• If n is omitted, 100 points are created.

• To generate a column, transpose the output of the linspace command.

© McGraw Hill LLC


Array Creation - logspace

• To create a row vector with a specific number of logarithmically


spaced points between two numbers, use the logspace
command.
• logspace(x1, x2, n) will create a logarithmically
spaced array of n points between 10x1 and 10x2
>>logspace(-1, 2, 4)
ans =
0.1000 1.0000 10.0000 100.0000
• If n is omitted, 100 points are created.
• To generate a column, transpose the output of the
logspace command.

© McGraw Hill LLC


Character Strings & Ellipsis
Alphanumeric constants are enclosed by apostrophes (')
>> f = 'Miles ';
>> s = 'Davis'
Concatenation: putting together two strings can be done through square brackets
>> x = [f s]
x =
Miles Davis
Ellipsis (...): Used to continue long lines
>> a = [1 2 3 4 5 ...
6 7 8]
a =
1 2 3 4 5 6 7 8
You cannot use an ellipsis within single quotes to continue a string. But you can
piece together shorter strings with ellipsis
>> quote = ['Any fool can make a rule,' ...
' and any fool will mind it']
quote =
Any fool can make a rule, and any fool will mind it
© McGraw Hill LLC
Some Useful Character Functions
Function Description
n = length(s) Number of characters, n, in a string, s.
b = strcmp(s1,s2) Compares two strings, s1 and s2; if equal
returns true (b = 1). If not equal , returns
false (b = 0).
n = str2num(s) Converts a string, s, to a number, n.
s = num2str(n) Converts a number, n, to a string, s.
s2 = strrep(s1,c1,c2) Replaces characters in a string with
different characters
i = strfind(s1,s2) Returns the starting indices of any
occurrences of the string s2 in the string s1
S = upper(s) Converts a string to upper case
s = lower(S) Converts a string to lower case
© McGraw Hill LLC
Mathematical Operations
Mathematical operations in MATLAB can be performed on both
scalars and arrays.
The common operators, in order of priority, are:
∧ Exponentiation 4∧2=8
− Negation (unary operation) −8 = −8
∗ Multiplication and Division 2 ∗ pi = 6.2832
∕ pi/4 = 0.7854
∖ Left Division 6\2 = 0.3333
+ Addition and Subtraction 3+5=8
− 3 − 5 = −2

Within each precedence level, operators are evaluated from left


to right
© McGraw Hill LLC
Order of Operations
The order of operations is set first by parentheses, then by the default order given
above, then left-to-right:
• y = −4 ^ 2 gives y = −16
since the exponentiation happens first due to its higher default priority, but

• y = (−4) ^ 2 gives y = 16
since the negation operation on the 4 takes place first because of the
parentheses

• y = 8/2*6 gives y = 24
since the left-to-right rule implements the division first to give 4 and then the
multiplication to give 4*6 to yield 24
© McGraw Hill LLC
Complex Numbers
All the operations listed in the previous slides can be used with
complex quantities (that is, values containing an imaginary part
entered using i or j and displayed using i)
>> x = 2+i*4; (or 2+4i, or 2+j*4, or 2+4j)
>> y = 16;
>> 3 * x
ans =
6.0000 +12.0000i
>> x+y
ans =
18.0000 + 4.0000i
>> x' % Compute complex Conjugate transpose
ans =
2.0000 - 4.0000i

© McGraw Hill LLC


Vector-Matrix Calculations
• MATLAB can also perform operations on vectors and matrices.
• The * operator for matrices is defined as the outer product or what is commonly
called “matrix multiplication.”
• The number of columns of the first matrix must match the number of rows in the second
matrix.
• The size of the result will have as many rows as the first matrix and as many columns as the
second matrix.
• The exception to this is multiplication by a 1 by 1 matrix, which is actually an array
operation.
• The ^ operator for matrices results in the matrix being matrix-multiplied by
itself a specified number of times.
• Note - in this case, the matrix must be square!

© McGraw Hill LLC


Element-by-Element Calculations
• At times, you will want to carry out calculations item by item in a matrix or vector.
• The MATLAB manual calls these array operations.
• They are also often referred to as element-by-element operations.
• MATLAB defines .* and ./ (note the dots) as the array multiplication and array
division operators.
• For array operations, both matrices must be the same size or one of the matrices must be 1 by 1
(that is, a scalar).
Array exponentiation (raising each element to a corresponding power in another
matrix) is performed with .^
• Again, for array operations, both matrices must be the same size or one of the matrices must be
1 by 1

© McGraw Hill LLC


Built-In Functions
• There are several built-in functions you can use to create and manipulate data.
• The built-in help function can give you information about both what exists and
how those functions are used:
• help elmat: will list the elementary matrix creation and manipulation functions, including
functions to get information about matrices.
• help elfun: will list the elementary math functions, including exponential, complex,
rounding, and remainder functions.

• The built-in lookfor command will search help files for occurrences of text and
can be useful if you know a function’s purpose but not its name

© McGraw Hill LLC


Graphics
• MATLAB has a powerful suite of built-in graphics functions.

• Two of the primary functions are plot (for plotting 2-D data) and
plot3 (for plotting 3-D data).

• In addition to the plotting commands, MATLAB allows you to label


and annotate your graphs using the title, xlabel, ylabel, and
legend commands.

© McGraw Hill LLC


𝑑𝑣
Plotting Example: problem
𝑑𝑡
t = [0:2:20]’;
g = 9.81; m = 68.1; cd = 0.25;
v = sqrt(g*m/cd) * tanh(sqrt(g*cd/m)*t);
plot(t, v)

© McGraw Hill LLC


Plotting Annotation Example
title('Plot of v versus t')
xlabel('Values of t')
ylabel('Values of v')
grid

Access the text alternative for slide images.

© McGraw Hill LLC


Plotting Options
• When plotting data, MATLAB can use several different colors, point
styles, and line styles.
• These are specified at the end of the plot command using plot specifiers (See
help plot).
• The default case for a single data set is to create a blue line with no
points.
• If a line style is specified with no point style, no point will be drawn at the
individual points;
• similarly, if a point style is specified with no line style, no line will be drawn.
• Examples of plot specifiers:
• ‘ro:’ - red dotted line with circles at the points.
• ‘gd’ - green diamonds at the points with no line.
• ‘m--’ - magenta dashed line with no point symbols.

© McGraw Hill LLC


Other Plotting Commands
hold on and hold off
• hold on tells MATLAB to keep the current data plotted and add the results of
any further plot commands to the graph. This continues until the hold off
command, which tells MATLAB to clear the graph and start over if another
plotting command is given. hold on should be used after the first plot in a
series is made.
subplot(m, n, p)
• subplot splits the figure window into an mn array of small axes and makes
the pth one active. Note - the first subplot is at the top left, then the numbering
continues across the row. This is different from how elements are numbered
within a matrix!

© McGraw Hill LLC


Questions

© McGraw Hill LLC


Programming with MATLAB

© McGraw Hill LLC


Objectives: Part 1
• Learning how to create well-documented M-files in the edit window and
invoke them from the command window.
• Understanding how script and function files differ.
• Understanding how to incorporate help comments in functions.
• Knowing how to set up M-files so that they interactively prompt users for
information and display results in the command window.
• Understanding the role of subfunctions and how they are accessed.
• Knowing how to create and retrieve data files.

© McGraw Hill LLC


Objectives: Part 2
• Learning how to write clear and well-documented M-files by employing
structured programming constructs to implement logic and repetition.
• Recognizing the difference between if...elseif and switch
constructs.
• Recognizing the difference between for...end and while structures.
• Understanding what is meant by vectorization and why it is beneficial.
• Knowing how to animate MATLAB plots.
• Understanding how anonymous functions can be employed.
• Anonymous functions can accept multiple inputs and return one output

© McGraw Hill LLC


M-files

• Whereas commands can be entered directly to the command


window, MATLAB also allows you to put commands in text
files called M-files.
• M-files are so named because the files are stored with an .m
extension.
• There are two main kinds of M-file
• Script files.
• Function files.

© McGraw Hill LLC


Script Files
• A script file is merely a set of MATLAB commands that are saved on
a file.
• when MATLAB runs a script file, it is as if you typed the characters stored in
the file on the command window.

• Scripts can be executed either by (make sure to save your file first):
• typing their name (without the .m) in the command window, by selecting the
Debug, Run (or Save and Run) command in the editing window, or
• by hitting the F5 key while in the editing window.

© McGraw Hill LLC


Function Files

• Function files serve an entirely different purpose from script


files.
• Function files can accept input arguments from the user and
return outputs to the command window.
• Note: the variables created and manipulated within the function do not
impact the command window.
• Function files are commonly used to perform useful tasks that
you might want to use again in other M-files.

© McGraw Hill LLC


Function File Syntax
The general syntax for a function is:
function outvar = funcname(arglist)
% helpcomments
statements
outvar = value;
where
• outvar: output variable name.
• funcname: function’s name.
• arglist: input argument list; comma-delimited list of values that the function requires
to execute properly.
• helpcomments: text to show with help funcname.
• statements: MATLAB commands for the function.
© McGraw Hill LLC
Subfunctions
• A function file can contain a single function, but it can also contain a
primary function and one or more subfunctions
• The primary function is whatever function is listed first in the M-file
• its function name should be the same as the file name.
• Subfunctions are listed below the primary function.
• Note that they are only accessible by the main function and subfunctions within
the same M-file and not by the command window or any other functions or
scripts.

© McGraw Hill LLC


Input

The easiest way to get a value from the user is the input
command:
• n = input('promptstring')
MATLAB will display the characters in promptstring, and whatever value is
typed is stored in n.
• For example, if you type pi, n will store 3.1416…

• n = input('promptstring', 's')
MATLAB will display the characters in promptstring, and whatever characters
are typed will be stored as a string in n.
• For example, if you type pi, n will store the letters p and i in a 21 char array.

© McGraw Hill LLC


Output
• The easiest way to display the value of a matrix is to type its
name, but that will not work in function or script files. Instead,
use the disp command:

• disp(value)
• will show the value on the screen.

• If value is a string, enclose it in single quotes. For example,


disp('Yes') will display Yes

© McGraw Hill LLC


Formatted Output
• For formatted output, or for output generated by combining variable
values with literal text, use the fprintf command:
• fprintf('format', x, y,...)
• where format is a string specifying how you want the value of the variables
x, y, and more to be displayed - including literal text to be printed along with
the values.

• The values in the variables are formatted based on format codes or format
specifiers as highlighted in the next slide.

© McGraw Hill LLC


Format and Control Codes
Within the format string, the following format codes define how a numerical value is
displayed:
%d - integer format
%e - scientific format with lowercase e
%E - scientific format with uppercase E
%f - decimal format
%g - the more compact of %e or %f
The following control codes produce special results within the format string:
\n - start a new line
\t - tab
\\ - print the \ character
Example of including text in a format string
fprintf('The value of pi is %8.4f \n',pi)

The value of pi is 3.1416

© McGraw Hill LLC


Creating and Accessing Files
• MATLAB has a built-in file format that may be used to save and load the
values in variables.
• save filename var1 var2 ... varn
• saves the listed variables into a file named filename.mat.
• If no variable is listed, all variables are saved.
• load filename var1 var2 ...varn
• loads the listed variables from a file named filename.mat.
• If no variable is listed, all variables in the file are loaded.

• Note about *.mat files: these are not text files!


© McGraw Hill LLC
ASCII Files
• To create user-readable files (i.e., *.txt files), append the flag -ascii
to the end of a save command.
• This will save the data to a text file in the same way that disp sends the data
to a screen.
• Note that in this case, MATLAB does not append anything to the file name so
you may want to add an extension such as .txt or .dat.

• To load a rectangular array from a text file, simply use the load
command and the file name. The data will be stored in a matrix with
the same name as the file (but without any extension).

© McGraw Hill LLC


Structured Programming
• Structured programming allows MATLAB to make decisions or selections
based on conditions of the program.
• Decisions in MATLAB are based on the result of logical and relational
operations and are implemented with if, if…else, and if…elseif
structures.
• Selections in MATLAB are based on comparisons with a test expression
and are implemented with switch structures.

© McGraw Hill LLC


Relational Operators
Summary of relational operators in MATLAB:

Example Operator Relationship


x == 0 == Equal
unit ~= ‘m’ ~= Not equal
a < 0 < Less than
s > t > Greater than
3.9 <= a/3 <= Less than or equal to
r >= 0 >= Greater than or equal to

© McGraw Hill LLC


Logical Operators
~x (Not): true if x is false (or zero); false
otherwise

x & y (And): true if both x and y are true


(or non-zero)

x || y (Or): true if either x or y are true (or


non-zero)

© McGraw Hill LLC


Order of Operations
• Priority can be set using:
• parentheses.
• After that, Mathematical expressions are highest priority,
• followed by relational operators,
• followed by logical operators.
• All things being equal, expressions are performed from left to right.
• Not is the highest priority logical operator, followed by And and finally Or
• Generally, do NOT combine two relational operators (e.g., through a comma)!
• If x=5, 3<x<4 should be false (mathematically), but it is calculated as an expression
in MATLAB as: 3<5<4, which leads to true<4 at which point true is converted to 1,
and 1<4 is true!
• Instead use: (3<x)&(x<4) to properly evaluate.

© McGraw Hill LLC


Decisions
• Decisions are made in MATLAB using if structures, which may also
include several elseif branches and possibly a catch-all else
branch.
• Deciding which branch runs is based on the result of conditions which
are either true or false.
• If an if tree hits a true condition, that branch (and that branch only) runs, then
the tree terminates.
• If an if tree gets to an else statement without running any prior branch, that
branch will run.
• Note - if the condition is a matrix, it is considered true if and only if (iff)
all entries are true (or non-zero).
© McGraw Hill LLC
Selections
• Selections are made in MATLAB using switch structures,
which may also include a catch-all otherwise choice.
• Deciding which branch runs is based on comparing the value
in some test expression with values attached to different
cases.
• If the test expression matches the value attached to a case, that case’s
branch will run.
• If no cases match and there is an otherwise statement, that branch
will run.

© McGraw Hill LLC


Loops
• Another programming structure involves loops, where the
same lines of code are run several times. There are two types
of loop:
• A for loop ends after a specified number of repetitions established by the
number of columns given to an index variable.
• A while loop ends on the basis of a logical condition.

© McGraw Hill LLC


for Loops
One common way to use a for…end structure is:
for index = start:step:finish
statements
end
where the index variable takes on successive values in the
vector created using the : operator.

© McGraw Hill LLC


Vectorization
Sometimes, it is more efficient to have MATLAB perform
calculations on an entire array rather than processing an array
element by element. This can be done through vectorization.

for loop Vectorization


i = 0; t = 0:0.02:50;
for t = 0:0.02:50 y = cos(t);
i = i + 1;
y(i) = cos(t);
end
© McGraw Hill LLC
while Loops
• A while loop is fundamentally different from a for loop since while loops
can run an indeterminate number of times.
• The general syntax is
while condition
statements
end
• where the condition is a logical expression.
• If the condition is true, the statements will run and when that is finished, the loop will again
check on the condition.

• Note - though the condition may become false as the statements are
running, the only time it matters is after all the statements have run.

© McGraw Hill LLC


Early Termination
• Sometimes it will be useful to break out of a for or while loop early
• this can be done using a break statement, generally in conjunction with an if
structure.
• Example:
x = 24
while (1)
x = x − 5
if x < 0, break, end
end
• will produce x values of 24, 19, 14, 9, 4, and -1, then stop.

© McGraw Hill LLC


continue Command
• The continue command jumps to the loop’s end statement and then
back to the loop’s initial statement (for or while) allowing the loop to
continue until the completion condition is met.
• Example:
for i = 1:100
if mod (i, 17)~=0
continue
end
disp([num2str(i)‘ is evenly divisible by 17’])
end

• will display all the numbers up to 100 that are evenly divisible by 17.

© McGraw Hill LLC


Animation
• Two ways to animate plots in MATLAB:
• Using looping with simple plotting functions.
• This approach merely replots the graph over and over again.
• Important to use the axis command so that the plots scales are fixed.

• Using special function: getframe and movie.


• This allows you to capture a sequence of plots (getframe) and then play
them back (movie).

© McGraw Hill LLC


Example

The (x, y) coordinates of a projectile can be generated as a function


of time, t, with the following parametric equations

x  v0 cos  0 t 

y  v0 sin  0 t   0.5 gt 2
where v0  initial velocity ( m s )
 0  initial angle (radians)
g  gravitational constant (= 9.81m s )
2

© McGraw Hill LLC


Script for Animation
The following code illustrates both approaches:
clc,clf,clear
g=9.81; theta0=45*pi/180; v0=5;
t(1)=0;x=0;y=0;
plot(x,y,'o','MarkerFaceColor','b','MarkerSize',8)
axis([0 3 0 0.8])
M(1)=getframe;
dt=1/128;
for j = 2:1000
t(j)=t(j−1)+dt;
x=v0*cos(theta0)*t(j);
y=v0*sin(theta0)*t(j)−0.5*g*t(j)^2;
plot(x,y,'o','MarkerFaceColor','b','MarkerSize',8)
axis([0 3 0 0.8])
M(j)=getframe;
if y<=0, break, end
end
pause
movie(M,1)
© McGraw Hill LLC
Result

Access the text alternative for slide images.

© McGraw Hill LLC


Nesting and Indentation
• Structures can be placed within other structures.
• For example, the statements portion of a for
loop can be comprised of an
if...elseif...else structure.

• For clarity of reading, the statements of a


structure are generally indented to show which
lines of controlled are under the control of which
structure.

© McGraw Hill LLC


Anonymous Functions
• Anonymous functions are simple one-line functions created without the
need for an M-file
fhandle = @(arg1, arg2, ...) expression

• Example: create a handle to an anonymous function that finds the square of a number:

sqr = @(x) x.^2; %

• Variable sqr is a function handle. The @ operator creates the handle, and the parentheses () immediately after the @
operator include the function input arguments. This anonymous function accepts a single input x, and implicitly
returns a single output, an array the same size as x that contains the squared values.

• Find the square of a particular value (5) by passing the value to the function handle, just as you would pass an input
argument to a standard function.

• a = sqr(25) % Will print 5


© McGraw Hill LLC
Inline Functions
• Inline functions are essentially the same as anonymous functions, but with a
different syntax:
fhandle = inline('expression', 'arg1', 'arg2',...)
% Define the inline functon 'z'
z = inline('x.^a','x', 'a');
% Call the function with explicit variables
y = z(1:10,2)
%y =
1 4 9 16 25 36 49 64 81 100

• Note1: Anonymous functions can access the values of variables in the


workspace upon creation, while inline functions cannot.
• Note2: inline is an eval wrapper and is much slower than anonymous fcns.

© McGraw Hill LLC


Function Functions
• Function functions are functions that operate on other functions
which are passed to it as input arguments.
• The input argument to the Function may be the handle of an
anonymous or inline function, the name of a built-in function, or
the name of a M-file function.
• Using function functions will allow for more dynamic
programming.

© McGraw Hill LLC


Example
function myfun(infun)
x = 0:0.1:pi;
y = infun(x);
plot(x,y)
end

then call it with a function handle:

myfun(@sin)

© McGraw Hill LLC


Questions

© McGraw Hill LLC


Roundoff Errors

© McGraw Hill LLC


Roundoff Errors

• Roundoff errors arise because digital computers cannot


represent some quantities exactly.
• There are two major facets of roundoff errors involved in
numerical calculations:
1. Digital computers have size and precision limits on their ability to
represent numbers.
2. Certain numerical manipulations are highly sensitive to roundoff
errors.

© McGraw Hill LLC


Computer Number Representation

• MATLAB stores floating-point numbers according to the IEEE 754 double-


precision standard.
• Eight bytes (64 bits) are used to represent a floating-point number:
𝑠𝑖𝑔𝑛 𝑒−1023
𝑛 = −1 1. 𝑏51 . 𝑏50 … 𝑏0 2 × 2

© McGraw Hill LLC


Computer Number Representation

• Eight bytes (64 bits) are used to represent a floating-point number:

𝑛 = −1 𝑠𝑖𝑔𝑛 1. 𝑏51 . 𝑏50 … 𝑏0 × 2𝑒−1023


2

52
= −1 𝑠𝑖𝑔𝑛 1+෍ 𝑏52−𝑖 2−𝑖 × 2𝑒−1023 = ±(1 + 𝑓) × 2𝑒−1023
𝑖=1

• The sign is determined by 1 reserved sign bit


• The mantissa f or Significand precision is determined by a 52-bit binary
number
• The exponent e is determined by an 11-bit unsigned integer from 0 to 2047
• In biased form: 1023 is subtracted from the number to get e as shown above
© McGraw Hill LLC
Floating Point Ranges
By convention, the 11 bits used for the exponent translates into a
numerical range from −1,023 to 1,023.
The largest possible number MATLAB can store has
• f of all 1’s, giving a significand of 1 + 1 − 2−52 = 2 − 2−52 or approximately 2.
• e of 111111111102 , giving an exponent of 2046 − 1023 = 1023.
• This yields approximately 21023  1.7997 10308.

The smallest possible number MATLAB can store with full


precision has
• f of all 0’s, giving a significand of 1.
• e of 000000000012 , giving an exponent of 1 − 1023 = − 1022.
• This yields 21022  2.225110308.
© McGraw Hill LLC
Note on the Exponent e
• Note: Exponents e range from −1022 to +1023 because exponents of
−1023 (all 0’s) and +1024 (all 1’s) are reserved for special numbers.
• https://en.wikipedia.org/wiki/Double-precision_floating-point_format

© McGraw Hill LLC


Floating Point Precision

• The 52 binary bits for the mantissa f correspond to about 15


to 16 base-10 digits.

• The machine epsilon i.e., the maximum relative error between


a number and MATLAB’s representation of that number, is
thus:
52 16
2  2.2204 10

© McGraw Hill LLC


Roundoff Errors with
Arithmetic Manipulations
• Roundoff error can happen in several circumstances other than just storing
numbers - for example:
• Large computations - if a process performs a large number of
computations, roundoff errors may build up to become significant.
• Adding a Large and a Small Number - Since the small number’s mantissa
is shifted to the right to be the same scale as the large number, digits are
lost.
• Smearing - Smearing occurs whenever the individual terms in a summation
are larger than the summation itself.
 x  10   x  10
20 20
is mathematically okay, but in Matlab if we assume x=1
x  1;  x  1020   x gives a 0 in MATLAB!

© McGraw Hill LLC


The End

© McGraw Hill LLC

You might also like