MATLAB 1 Mathematical Software Symbolic Math Packages - This - - PowerPoint PPT Presentation

matlab
SMART_READER_LITE
LIVE PREVIEW

MATLAB 1 Mathematical Software Symbolic Math Packages - This - - PowerPoint PPT Presentation

MATLAB 1 Mathematical Software Symbolic Math Packages - This amorphous set of packages can be used to perform symbolic analyses. These packages typically can solve algebraic and differential equations, can integrate and differentiate


slide-1
SLIDE 1

MATLAB

1

slide-2
SLIDE 2

Mathematical Software

  • Symbolic Math Packages - This amorphous set of packages can be used to perform symbolic analyses. These packages typically can

solve algebraic and differential equations, can integrate and differentiate symbolic expressions, and can simplify and manipulate algebraic expressions.

  • Maple - Produced by Waterloo Maple Inc., in Canada. It is somewhat smaller than its competitors, but is as powerful as any package available.

The syntax for this package is relatively intuitive for mathematicians. It has relatively powerful typesetting capabilities.

  • Mathematica - Produced by Wolfram Inc., in the U.S.. The syntax for this package is less intuitive than that for some, but is arguably more
  • consistent. The package is as powerful as any available, but tends to require more memory than some of its competitors. It also has powerful

typesetting abilities.

  • Macsyma - This was the first symbolic mathematics package, dating from the early 1980s, and produced at MIT. It is now free, and is available

for many platforms. Unfortunately, it suffers from perhaps the most obscure syntax of any package of its kind, and has relatively poor graphics.

  • Sympy, Sage, etc. - There are several packages for use in python that can do symbolic mathematics.
  • Numerical Packages - packages in this class excel at solving numerical problems. While some have limited symbolic capabilities,

they are best when programmed to run complicated algorithms. They can handle all problems involving numerical matrices and vectors.

  • Matlab - produced by the Mathworks in the U.S., this is the gold standard of the class of packages. It is probably the most-used mathematical

package for both mathematicians and engineers. For a price, it can have some symbolic capability.

  • Octave - this package is free, and does most of what Matlab does. While it lacks the symbolic toolbox and several other add-on features of

Matlab, and its graphics are not of the same standard, in the end it is an excellent and powerful free alternative, available for most platforms.

  • Numpy, Scipy, Matplotlib, Pylab etc .- There are several related packages for python that can mimic the numerical and plotting capabilities of

Matlab.

  • R, Stata, SPSS – These are numerical software pacakges specialized primarily for statistical computing.
  • Mathematical spreadsheets - we are aware of only one program in this class, used more by scientists and engineers than by
  • mathematicians. It is called Mathcad. It is not really a spreadsheet, but we refer to it that way because the position of expressions
  • n a page determines their order of execution. It has some symbolic capability, but it is best at doing analyses that involve

changing a parameter and running a sequence of calculations anew.

2

slide-3
SLIDE 3

MATLAB

  • MATLAB is a multi-paradigm (functional, imperative, procedural, object-oriented)

numerical computing environment and programming language. A proprietary programming language developed by MathWorks, MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages, including C, C++, C#, Java, Fortran and Python.

  • The program MATLAB dates from the mid-1980s. It came out of work by Cleve Moler,

who remains the head of MathWorks. It was designed with relatively humble objectives: to provide a simple interface to high-quality numerical procedures for solving mathematical problems written in Fortran. Indeed, MATLAB stands for Matrix Laboratory. It has effectively become the standard package for mathematicians and engineers who need to do quick-and-dirty estimates, simulations, designs, and tests of algorithms.

  • Although MATLAB is intended primarily for numerical computing, an optional toolbox

uses a symbolic engine called MuPAD, allowing access to symbolic computing abilities.

3

slide-4
SLIDE 4

MATLAB Basics

  • When you start MATLAB, regardless of the details of the interface, you should

notice immediately that it is basically just a command line. You type commands, hit <Enter>, and the commands are executed. The basic syntax is very natural to anyone who has used a computer before. For example, to do a simple arithmetic calculation, just type it in and press <Enter>.

>> 3+4 ans = 7

  • This illustrates several basic notions behind Matlab. First, Matlab can do all basic

arithmetic operations with a very natural syntax. Second, Matlab requires that every computation be assigned to a variable.

  • As well as in Linux or Windows shell all commands are executed in the context of

a certain environment. In MATLAB such environment called the Workspace. If you are running MATLAB in graphical mode, by default you should see the Workspace panel on the right.

4

slide-5
SLIDE 5

MATLAB Basics

  • If you do not specify the name of the variable, MATLAB uses a default name: ans. MATLAB reuses the name

ans as needed, so if you want to keep the result of a computation for reference later in a session, you should assign it to a different variable. For example, the following just assigns the value 7 to a variable called seven:

>> seven=3+4 seven = 7

  • Every time a new variable is assigned, MATLAB adds it to the workspace so it can be accessed any time later.

We may view the contents of the variable seven at any time simply by typing its name:

>> seven seven = 7

  • One may use variables interchangeably with the numbers or objects that they represent. For example, we

could define a variable called ten by

>> ten=seven+3 ten = 10

  • Matlab uses “+” to denote addition, “-” to denote subtracon, “*” for mulplicaon, “/” for division, and “ˆ”

to denote exponentiation:

>> myvariable=2*(ten-2)+(ten/5)^2 myvariable = 20 5

slide-6
SLIDE 6

MATLAB Basics: Identifier Names

  • Variable names are examples of identifier names. The rules for identifier names

are as follows:

1. The name must begin with a letter of the alphabet. After that, the name can contain letters, digits, and the underscore character (e.g., value_1), but it cannot have a space. 2. There is a limit to the length of the name; the built-in function namelengthmax tells what this maximum length is (any extra characters are truncated). 3. MATLAB is case-sensitive, which means that there is a difference between upper- and lowercase letters. So, variables called mynum, MYNUM, and Mynum are all different (although this would be confusing and should not be done). 4. Although underscore characters are valid in a name, their use can cause problems with some programs that interact with MATLAB, so some programmers use mixed case instead (e.g., partWeights instead of part_weights). 5. There are certain words called reserved words, or keywords, that cannot be used as variable names. 6. Names of built-in functions can, but should not, be used as variable names.

  • Obviously, variable names should always be mnemonic, which means that they

should make some sense. For example, if the variable is storing the radius of a circle, a name such as radius would make sense; x probably wouldn’t.

6

slide-7
SLIDE 7

MATLAB Basics: Variables

  • The following commands relate to variables:
  • who – shows variables that have been defined in this Command Window (this

just shows the names of the variables)

  • whos – shows variables that have been defined in this Command Window

(this shows more information on the variables, similar to what is in the Workspace Window)

  • clear – clears out all variables so they no longer exist
  • clear variablename – clears out a particular variable
  • clear variablename1 variablename2 – clears out a list of variables

(note: separate the names with spaces)

  • Note that to suppress automatic output of the result of particular

command one should add semicolon at the end of this command.

7

slide-8
SLIDE 8

MATLAB Basics: Data Types

  • Every variable has a type associated with it. MATLAB supports many types,

which are called classes. Essentially, a class is a combination of a type and the operations that can be performed on values of that type. Note that different classes may have the same operations define but the result of applying them may be different.

  • Users can define their own custom types/classes.
  • Note that MATLAB has dynamic typing, which means that type of variable

is inferred automatically and you may not specify it explicitly.

  • To force MATLAB to assign specific type to a variable one can use the

following syntax variablename = typename(variablevalue)

  • To see what class is assigned to a particular variable one can use

class(variablename)command.

8

slide-9
SLIDE 9

MATLAB Basics: Data Types

  • There are 16 fundamental classes in MATLAB:
  • double, single - floating-point numbers with double and single precision.
  • int8, uint8, int16, uint16, int32, uint32, int64, uint64 - use for signed and unsigned whole

numbers and provide more efficient use of memory.

  • char, string - data types for text.
  • logical - used in relational conditions or to test state and can have only one of two values: true or false.
  • function_handle - pointer to a function which enables passing a function to another function.
  • table - rectangular container for mixed-type, column-oriented data.
  • struct - fields store arrays of varying classes and sizes.
  • cell - stores arrays of varying classes and sizes.
  • Each of these classes is in the form of a matrix or array with the exception of function handles.
  • MATLAB provides various functions for converting, a value from one data type to another such as int2str
  • r str2num. See this link for more: https://www.mathworks.com/help/matlab/data-type-conversion.html.
  • Apart from class function MATLAB also provides some more specific functions for data type identifications

such as ischar or isfloat. See this link for more: https://www.mathworks.com/help/matlab/data-type- identification.html

  • More on data types could be found here: https://www.mathworks.com/help/matlab/data-types_data-

types.html.

9

slide-10
SLIDE 10

MATLAB Basics: Vectors and Matrices

  • As we already mentioned, MATLAB is short for matrix laboratory, so

everything in MATLAB is written to work with vectors and matrices.

  • Vectors and matrices are used to store sets of values, all of which are the

same type. A matrix can be visualized as a table of values. The dimensions

  • f a matrix are r x c, where r is the number of rows and c is the number of

columns.

  • A vector can be either a row vector or a column vector. If a vector has n

elements, a row vector would have the dimensions 1 x n and a column vector would have the dimensions n x 1. A scalar (one value) has the dimensions 1 x 1. Therefore, vectors and scalars are actually just special cases of matrices.

10

slide-11
SLIDE 11

Vectors Basics

  • There are several ways to create row vector variables. The most direct way is to put the values that you want

in the vector in square brackets, separated by either spaces or commas. For example, both of these assignment statements create the same vector v that has four elements:

>> v = [1 2 3 4] v = 1 2 3 4 >> v = [1,2,3,4] v = 1 2 3 4

  • If, as in the preceding examples, the values in the vector are regularly spaced, the colon operator can be

used to iterate through these values. For example, 1:5 results in all of the integers from 1 to 5 inclusive:

>> vec = 1:5 vec = 1 2 3 4 5

  • Often we want to create a sequence of points with some uniform spacing other than one. That calls for

another term in the definition for the vector:

>> v = 1:.5:4 v = 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000

11

slide-12
SLIDE 12

Vectors Basics

  • One way to create a column vector is to explicitly put the values in square

brackets, separated by semicolons (rather than commas or spaces):

>> c = [1; 2; 3; 4] c = 1 2 3 4

  • There is no direct way to use the colon operator to get a column vector. However,

any row vector created using any method can be transposed to result in a column

  • vector. In general, the transpose of a matrix is a new matrix in which the rows and

columns are interchanged. For vectors, transposing a row vector results in a column vector, and transposing a column vector results in a row vector. In MATLAB, the apostrophe is built in as the transpose operator.

>> r = 1:3; >> c = r' c = 1 2 3

12

slide-13
SLIDE 13

Vectors Basics

  • The elements in a vector are numbered sequentially; each element number is called the index, or subscript. In MATLAB, the

indices start at 1. A particular element in a vector is accessed using the name of the vector variable and the index or subscript in

  • parentheses. For example, the fifth element in the vector v is a 9:

>> v(5) ans = 9

  • A subset of a vector, which would be a vector itself, can also be obtained using the colon operator. For example, the following

statement would get the fourth through sixth elements of the vector v, and store the result in a vector variable b:

>> b = v(4:6) b = 7 9 3

  • Any vector can be used for the indices into another vector, not just one created using the colon operator. The indices do not need

to be sequential. For example, the following would get the first, tenth, and fifth elements of the vector v:

>> v([1 10 5]) ans = 1 15 9

  • The vector [1 10 5] is called an index vector; it specifies the indices in the original vector that are being referenced.
  • The value stored in a vector element can be changed by specifying the index or subscript. For example, to change the second

element from the preceding vector b to now store the value 11 instead of 9:

>> b(2) = 11 b = 7 3 11

  • If we specify an index that refer to the element that does not exists, then the element would be automatically created. If there is

a gap between the current vector and the element being added, MATLAB will fill in with zeros.

13

slide-14
SLIDE 14

Matrices Basics

  • Creating a matrix variable is simply a generalization of creating row and column vector variables.

That is, the values within a row are separated by either spaces or commas, and the different rows are separated by semicolons. For example, the matrix variable mat is created by explicitly entering values:

>> mat = [4 3 1; 2 5 6] mat = 4 3 1 2 5 6

  • There must always be the same number of values in each row. If you attempt to create a matrix in

which there are different numbers of values in the rows, the result will be an error message.

  • Iterators can be used for the values in the rows using the colon operator. For example:

>> mat = [2:4; 3:5] mat = 2 3 4 3 4 5

14

slide-15
SLIDE 15

Matrices Basics

  • To refer to matrix elements, the row and then the column subscripts are given in parentheses (always the row first and then the

column). For example, this creates a matrix variable mat and then refers to the value in the second row, third column of mat:

>> mat = [2:4; 3:5] mat = 2 3 4 3 4 5 >> mat(2,3) ans = 5

  • It is also possible to refer to a subset of a matrix. For example, this refers to the first and second rows, second and third columns:

>> mat(1:2,2:3) ans = 3 4 4 5

  • Using just one colon by itself for the row subscript means all rows, regardless of how many, and using a colon for the column

subscript means all columns. For example, this refers to all columns within the first row or, in other words, the entire first row:

>> mat(1,:) ans = 2 3 4

  • If a single index is used with a matrix, MATLAB unwinds the matrix column by column.

15

slide-16
SLIDE 16

Empty Vectors

  • An empty vector (a vector that stores no values) can be created using empty square brackets:

>> evec = [] evec = []

  • Values can then be added to an empty vector by concatenating, or adding, values to the existing vector. The following statement

takes what is currently in evec, which is nothing, and adds a 4 and 7 to it.

>> evec = [evec 4 7] evec = 4 7

  • Empty vectors can also be used to delete elements from vectors. For example, to remove the second and the third elements from

a vector, the empty vector is assigned to the seconds and the third columns:

>> vec = 4:8 vec = 4 5 6 7 8 >> vec(2:3) = [] vec = 4 7 8

  • Individual elements cannot be removed from matrices, as matrices always have to have the same number of elements in every
  • row. However, entire rows or columns could be removed from a matrix. For example, to remove the second column:

>> mat(:,2) = []

16

slide-17
SLIDE 17

Matrices Basics

  • An individual element in a matrix can be modified by assigning a new value to it.

>> mat = [2:4; 3:5]; >> mat(1,2) = 11 mat = 2 11 4 3 4 5

  • An entire row or column could also be changed. For example, the following replaces the

entire second row with values from a vector obtained using the colon operator:

>> mat(2,:) = 5:7 mat = 2 11 4 5 6 7

  • Notice that as the entire row is being modified, a row vector with the correct length

must be assigned. Any subset of a matrix can be modified as long as what is being assigned has the same number of rows and columns as the subset being modified.

17

slide-18
SLIDE 18

Matrices Basics

  • To extend a matrix an individual element could not be added as that would mean there

would no longer be the same number of values in every row. However, an entire row or column could be added. For example, the following would add a fourth column to the matrix:

>> mat(:,4) = [9 2]' mat = 2 11 4 9 5 6 7 2

  • Just as we saw with vectors, if there is a gap between the current matrix and the row or

column being added, MATLAB will fill in with zeros.

>> mat(4,:) = 2:2:8 mat = 2 11 4 9 5 6 7 2 0 0 0 0 2 4 6 8

18

slide-19
SLIDE 19

Dimensions

  • The length and size functions in MATLAB are used to find dimensions of

vectors and matrices.

  • The length function returns the number of elements in a vector.

>> vec = -2:1 vec =

  • 2 -1 0 1

>> length(vec) ans = 4

  • The size function returns the number of rows and columns in a vector or

matrix.

>> size(vec) ans = 1 4

19

slide-20
SLIDE 20

Other Ways to Initialize Matrices

  • To create a zero-matrix (with all elements equal to zero) you can use zeros(r, c) function, where r

(rows) and c (columns) parameters define dimensions of the matrix you want to create:

>> A = zeros(2, 3) A = 0 0 0 0 0 0

  • To create a matrix will all ones you can use ones(r, c). Meaning of parameters is the same:

>> A = ones(2,3) A = 1 1 1 1 1 1

  • To create a matrix with all ones on the main diagonal and zeros elsewhere (a square matrix of this kind

called identity matrix) you can use eye(r, c) function, where r (rows) and c (columns) parameters define dimensions of the matrix you want to create:

>> A = eye(2, 3) A = 1 0 0 0 1 0

20

slide-21
SLIDE 21

Other Ways to Initialize Matrices

  • Matrices of random numbers can be created using the rand function. If a single value n is passed to rand, an n x n matrix will be

created, or passing two arguments will specify the number of rows and columns:

>> rand(2) ans = 0.2311 0.4860 0.6068 0.8913 >> rand(1,3) ans = 0.7621 0.4565 0.0185

  • Matrices of random integers can be generated using randi; after the range is passed, the dimensions of the matrix are passed

(again, using one value n for an n x n matrix, or two values for the dimensions):

>> randi([10, 30], 2, 3) ans = 21 10 13 19 17 26

  • Note that the range can be specified for randi, but not for rand (the format for calling these functions is different).
  • Also note that rand creates a matrix of uniformly distributed pseudo-random numbers in [0; 1]. This matrix is typically seeded.

You can randomize it by first calling rng(). See these links for more details: https://www.mathworks.com/help/matlab/math/why-do-random-numbers-repeat-after-startup.html and https://www.mathworks.com/help/matlab/ref/rng.html

21

slide-22
SLIDE 22

Operations on Matrices

  • MATLAB handles matrix arithmetic just as easily as scalar arithmetic. The symbols for the operations are the

same, but their meaning is changed to that appropriate for matrix operations.

  • For example, let’s say that we want to multiply every element of a matrix m by 3. In MATLAB, we can simply

multiply m by 3 and store the result back in m in an assignment statement:

>> m = [3 7; 2 1]; >> m = m*3 m = 9 21 6 3

  • As another example, we can divide every element by 2:

>> m/2

  • Adding/Subtracting a number to/from matrix variable will result in adding/subtracting this number to/from

every element of the matrix:

>> (m+3)-5 m = 7 19 4 1

  • This operation is referred to as scalar multiplication. We are multiplying every element in a vector or matrix

by a scalar (or dividing every element in a vector or a matrix by a scalar).

22

slide-23
SLIDE 23

Operations on Matrices

  • Array operations are operations that are performed on vectors or matrices term by term or element by
  • element. This means that the two arrays (vectors or matrices) must be the same size to begin with. The

following examples demonstrate the array addition and subtraction operators:

>> v1 = 2:5 v1 = 2 3 4 5 >> v2 = [33 11 5 1] v2 = 33 11 5 1 >> v1 + v2 ans = 35 14 9 6 >> mata = [5:8; 9:-2:3] mata = 5 6 7 8 9 7 5 3 >> matb = reshape(1:8,2,4) % see this link to see what reshape does

https://www.mathworks.com/help/matlab/ref/reshape.html

matb = 1 3 5 7 2 4 6 8 >> mata - matb ans = 4 3 2 1 7 3 -1 -5

23

slide-24
SLIDE 24

Operations on Matrices

  • However, for any operation that is based on multiplication (which means multiplication, division, and

exponentiation), a dot must be placed in front of the operator for array operations. For example, for the exponentiation operator .^ must be used when working with vectors and matrices, rather than just the ^

  • perator. Squaring a vector, for example, means multiplying each element by itself so the .^ operator must

be used.

>> v = [3 7 2 1]; >> v ^ 2 ans = 9 49 4 1

  • Similarly, the operator .* must be used for array multiplication and ./ or .\ for array division. The

following examples demonstrate array multiplication and array division:

>> u = [2 3 4 5]; >> v .* u ans = 6 21 8 5 >> v ./ u ans = 1.5000 2.3333 0.5000 0.2000

  • Note that matrix multiplication is a very different operation, and will be covered in the next section.

24

slide-25
SLIDE 25

Operations on Matrices

  • If we omit dot while applying multiplication operator (*) to matrices, MATLAB will do

matrix multiplication as we know it from linear algebra (https://en.wikipedia.org/wiki/Matrix_multiplication).

>> A = [1 2; 3 4;]; >> A*A ans = 7 10 15 22

  • Using exponentiation operator (^) without preceding dot will produce n-th power of

matrix (which means matrix multiplied by itself n times), but not a matrix consisting of n- th powers of elements of the initial matrix.

>> A^5 ans = 1069 1558 2337 3406

  • Recall that if we want to multiply two matrices the number of columns of the first matrix

should be equal to the number of rows of the second matrix. This implies that n-th power of matrix can be computed only for square matrices.

25

slide-26
SLIDE 26

Operations on Matrices

  • \ operator may have unexpected meaning for matrices. If A is matrix and b is column vector,

then A\b command will result in solving system of linear equations A*x=b (see https://www.mathworks.com/help/symbolic/linsolve.html#btke0hr-32)

>> A = [1 3 -2; 3 5 6; 2 4 3] A = 1 3 -2 3 5 6 2 4 3 >> b = [5 7 8]' b = 5 7 8 >> A\b ans = -15.0000 8.0000 2.0000

26

slide-27
SLIDE 27

Dot Products and Cross Products

  • There are two specific operations that we can apply to vectors but not matrices: dot product (or inner product) and cross product.
  • There are two ways to compute dot product: use function called dot(v1, v2)or perform matrix multiplication of row-vector

v1 and column-vector v2.

>> v1 = [1 2 3]; >> v2 = [2 2 1]; >> dot(v1, v2) ans = 9 >> v1 * v2' ans = 9 >> dot(v1', v2’) % dot product for column vectors ans = 9

  • To compute cross product you can use function called cross(v1, v2).

>> cross(v1, v2) ans =

  • 4 5 -2
  • Remember that the dot product will produce a scalar and the cross product will produce a vector.

27

slide-28
SLIDE 28

Basic Matrix Functions

  • abs(x)- returns the absolute value of the entries of a matrix x.
  • det(x)- returns the determinant of the matrix x.
  • eig(x)- returns a vector containing the eigenvalues of the matrix x.
  • inv(x)- returns the inverse of the matrix x, if it exists.
  • norm(x)- returns the norm of the matrix x.
  • rank(x)- returns the rank of the matrix x.
  • null(x)- returns basis for the null space of matrix x.
  • lu(x)- returns LU decomposition of the matrix x.
  • rref(x)- returns reduced row echelon form (Gauss-Jordan elimination)
  • You can find more here https://www.mathworks.com/help/matlab/linear-

algebra.html

28

slide-29
SLIDE 29

Logical Vectors

  • Logical vectors use relational expressions that result in true/false values.
  • Relational operators can be used with vectors and matrices. For example, let’s say that there is a vector vec,

and we want to compare every element in the vector to 5 to determine whether it is greater than 5 or not. The result would be a vector (with the same length as the original) with logical true or false values.

>> vec = [5 9 3 4 6 11]; >> isg = vec > 5 isg = 0 1 0 0 1 1

  • To determine how many of the elements in the vector vec were greater than 5, the sum function could be

used on the resulting vector isg:

>> sum(isg) ans = 3

  • There are built-in functions in MATLAB, which are useful in conjunction with logical vectors or matrices; two
  • f these are the functions any and all. The function any returns logical true if any element in a vector

represents true, and false if not. The function all returns logical true only if all elements represent true.

>> any(isg) ans = 1 >> all(true(1,3)) ans =1

29

slide-30
SLIDE 30

Integers and Floating Point Numbers

  • The function find returns the indices of a vector that meet given criteria. For example, to find all of the

elements in a vector that are greater than 5:

>> vec = [5 3 6 7 2]; >> find(vec > 5) ans = 3 4

  • Note that for matrices, the find function will use linear indexing when returning the indices that meet the

specified criteria. For example:

>> A = [5 6 7 8; 9 7 5 3]; >> find(A == 5) ans = 1 6

  • The built-in function isequal checks if all elements of the given vectors are equal:

>> vec1 = [1 3 -4 2 99]; vec2 = [1 2 -4 3 99]; >> vec1 == vec2 ans = 1 0 1 0 1 >> isequal(vec1,vec2) ans = 0

  • However, one difference is that if the two arrays are not the same dimensions, the isequal function will

return logical 0, whereas using the equality operator will result in an error message.

30

slide-31
SLIDE 31

Trigonometric Functions, Exponents, Logarithms

  • Obviously, MATLAB provides standard trigonometric functions, exponents and logarithms which may be used

in a usual way:

>> x = pi/6 x = 0.5236 >> sin(x) ans = 0.5000

  • Note that these functions can be applied to matrices which will result in applying the function to every

element of the matrix:

>> A = [0 pi/6 pi/3; pi/4 pi/2 pi]; >> cos(A) ans = 1.0000 0.8660 0.5000 0.7071 0.0000 -1.0000

  • Check out these links for complete list of functions and for more details on usage:

https://www.mathworks.com/help/matlab/trigonometry.html and https://www.mathworks.com/help/matlab/exponents-and-logarithms.html

31

slide-32
SLIDE 32

Floating Point Variables

  • In computing, floating-point arithmetic is arithmetic using representation of real

numbers as an approximation so as to support a trade-off between range and

  • precision. A number is, in general, represented approximately to a fixed number
  • f significant digits (the significand) and scaled using an exponent in some fixed

base; the base for the scaling is normally two, ten, or sixteen. A number that can be represented exactly is of the following form:

  • Here significand is an integer, base is an integer greater than or equal to two, and

exponent is also an integer. For example:

  • The term floating point refers to the fact that a number's radix point (decimal

point, or, more commonly in computers, binary point) can "float"; that is, it can be placed anywhere relative to the significant digits of the number.

32

slide-33
SLIDE 33

Floating Point Variables

  • Precision of floating point number depends on how many bits may be used to represent

the variable. MATLAB supports two possible precisions: single and double.

  • single (single precision) is a binary format that occupies 32 bits (4 bytes): its

significand has a precision of 23 bits (about 7 decimal digits), exponent occupies 8 bits and 1 bit is used for sign representation. The maximum that can be represented is approximately 10^38. The minimum value is approximately 3×10^(-38).

  • double (double precision) is a binary format that occupies 64 bits (8 bytes): its

significand has a precision of 52 bits (about 7 decimal digits), exponent occupies 11 bits and 1 bit is used for sign representation. The maximum that can be represented is approximately 1.8×10^308. The minimum value is approximately 2.2×10^(-308).

  • Check out this link for more details:

https://www.mathworks.com/help/matlab/matlab_prog/floating-point-numbers.html

  • Check out this link for nice explanation by Prof Cooper:

http://www.math.wsu.edu/math/kcooper/M300/matlabfloat.php

33

slide-34
SLIDE 34

Integers

  • MATLAB has four signed and four unsigned integer classes. Signed types

enable you to work with negative integers as well as positive, but cannot represent as wide a range of numbers as the unsigned types because one bit is used to designate a positive or negative sign for the number. Unsigned types give you a wider range of numbers, but these numbers can

  • nly be zero or positive.
  • MATLAB supports 8-, 16-, 32-, and 64-bits storage for integer data. You can

save memory and execution time for your programs if you use the smallest integer type that accommodates your data. For example, you do not need a 32-bit integer to store the value 100.

  • Check out this link for more details:

https://www.mathworks.com/help/matlab/ref/reshape.html

34

slide-35
SLIDE 35

Constants

  • We have already seen how to get the pi constant.
  • MATLAB does not provide built-in way to use value of the e constant. Instead you can do the trick:

>> e = exp(1) e = 2.7183

  • Two other important constants to note are Inf and NaN. Inf denotes infinity. NaN means Not-a-Number, which can result from
  • perations which have undefined numerical results.

>> 1 / 0 ans = Inf >> (+Inf)+(-Inf) ans = NaN

  • To get floating point accuracy for given data type you can use eps(datatype). Actually the only two possible usages are just:

eps('single') and eps('double').

>> eps('double') ans = 2.2204e-16

  • For more see this link: https://www.mathworks.com/help/matlab/constants-and-test-matrices.html

35

slide-36
SLIDE 36

Characters and Strings

  • There are two data types that can represent text in MATLAB: character arrays and string arrays.
  • A character array is a sequence of characters, just as a numeric array is a sequence of numbers. A typical use is to store short

pieces of text as character vectors, such as c = 'Hello World’.

  • By character array we mean that, for example, text 'Hello’ is actually an array/vector of characters ‘H’, ‘e’, ‘l’, ‘l’

and ‘o’.

  • To create a character vector one should enclose a sequence of characters in single quotation marks.

>> chr = 'Hello, world' chr = 'Hello, world’

  • Since character vectors store characters as 1-by-N vectors, you can index directly into character vectors to get characters, or to

change them.

>> chr(8:12) ans = 'world' >> chr(1:5) = 'HELLO' chr = 'HELLO, world'

  • You can work with character vectors just as you would with arrays of any other type. For example, you can concatenate character

vectors.

>> street = '123 Maple St.'; >> city = 'Lakeview, MA 01234'; >> fullAddress = [street ', ' city] fullAddress = '123 Maple St., Lakeview, MA 01234'

36

slide-37
SLIDE 37

Characters and Strings

  • Each character is actually represented in the computer by an integer, with the alphabetical

interpretation only happening when text is printed to a screen or page.

letters = 'abcdef’; >> letters+1 ans = 98 99 100 101 102 103 >> char(letters+1) ans = 'bcdefg’ >> letters+'123456' ans = 146 148 150 152 154 156

  • So its important to remember that additon operator (+) does not concatenate text represented by

character arrays, but add codes of correspodning characters elementwise.

  • If we try '1' + ‘2’, we will get 99. The way to understand this is that characters are associated with

'ASCII codes': the integers that represent them. Thus the number 1 as an integer is represented in the computer by an integer 1, but the character '1' is represented by the integer 49. The character '2' has ASCII code 50, so that '1' + '2' = 49 + 50 = 99. In the same way, you can see that the ASCII code for 'a' is 97.

37

slide-38
SLIDE 38

Characters and Strings

  • You also can store text in string arrays. Each element of a string array stores a 1-by-N character vector.

Starting in MATLAB R2017a, you can create strings using double quotes.

>> str = "Welcome, friend" str = "Welcome, friend“

  • As an alternative, you can convert a character vector to a string using the string function.

>> chr = 'Hello, world'; >> str = string(chr) str = "Hello, world“

  • You can store multiple pieces of text in a string array. Each element of the array can contain a string of a

different size.

>> str = ["Mercury","Gemini","Apollo"; "Skylab","Skylab B","ISS"] str = 2×3 string array "Mercury" "Gemini" "Apollo" "Skylab" "Skylab B" "ISS"

  • Note that by specifying row and column number in parentheses we can access the whole string but not a

single character:

>> str(1, 1) + " and " + str(1, 2) ans = "Mercury and Gemini“

  • The above example also shows the result of applying addition operator (+) to strings: it does concatenation.

38

slide-39
SLIDE 39

Function Handles Example: Anonymous Functions

  • To complete our overview of MATLAB data types we will consider a particular example of function_handle data type

(function_handle can have broader use, but we will see it later).

  • An anonymous function (or in-line function) is a function that is not stored in a program file, but is associated with a variable

whose data type is function_handle. Anonymous functions can accept inputs and return outputs. They can contain only a single executable statement.

  • You may think of anonymous functions as a fast way of defining mathematical functions when working with command line (in
  • pposite to usual functions which are named, defined in scripts and can have multiple executable statements).
  • For example, create a handle to an anonymous function that finds the square of a number:

>> sqr = @(x) x.^2 sqr = function_handle with value: @(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.

>> sqr(25) ans = 625

39

slide-40
SLIDE 40

Anonymous Functions

  • Many MATLAB functions accept function handles as inputs so that you can evaluate

functions over a range of values. For example, find the integral of the sqr function from 0 to 1 by passing the function handle to the integral function:

q = integral(sqr,0,1);

  • You are not required to create a variable to use an anonymous function. Instead, you

can create a temporary function handle within an expression (which is indeed totally anonymous function), such as this call to the integral function:

q = integral(@(x) x.^2,0,1);

  • Function handles can store not only an expression, but also variables that the expression

requires for evaluation. For example, create a function handle to an anonymous function that requires coefficients a, b, and c.

a = 1.3; b = .2; c = 30; parabola = @(x) a*x.^2 + b*x + c;

  • Note that if you update a, b or c after defining the above function the changes will not

affect parabola.

40

slide-41
SLIDE 41

Anonymous Functions

  • You also can include anonymous function in definition other anonymous function. This is useful

for passing different parameters to a function that you are evaluating over a range of values. For example, you can solve the equation for varying values of c by combining two anonymous function

g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));

  • Here is how to derive this statement:

1. Write the integrand as an anonymous function: @(x) (x.^2 + c*x + 1) 2. Evaluate the function from zero to one by passing the function handle to integral: integral(@(x)

(x.^2 + c*x + 1),0,1)

3. Supply the value for c by constructing an anonymous function for the entire equation: g = @(c)

(integral(@(x) (x.^2 + c*x + 1),0,1));

  • The final function allows you to solve the equation for any value of c. For example:

g(2) ans = 2.3333

41

slide-42
SLIDE 42

Anonymous Functions

  • Anonymous functions may not have inputs. If your function does not require any inputs, use empty parentheses when you define

and call the anonymous function. For example:

>> t = @() datestr(now); % now returns current date/time, datestr converts date/time to a string >> d = t() d = 26-Jan-2012 15:11:47

  • Also anonymous functions can have multiple inputs or outputs. Anonymous functions require that you explicitly specify the input

arguments as you would for a standard function, separating multiple inputs with commas. For example, this function accepts two inputs, x and y:

>> myfunction = @(x,y) (x^2 + y^2 + x*y); >> x = 1; y = 10; >> z = myfunction(x,y) z = 111

  • However, you do not explicitly define output arguments when you create an anonymous function. If the expression in the

function returns multiple outputs, then you can request them when you call the function. Enclose multiple output variables in square brackets. For example, the ndgrid function can return as many outputs as the number of input vectors. This anonymous function that calls ndgrid can also return multiple outputs:

>> c = 10; >> mygrid = @(x,y) ndgrid((-x:x/c:x),(-y:y/c:y)); >> [x,y] = mygrid(pi,2*pi); >> z = sin(x) + cos(y); >> mesh(x,y,z)

42

slide-43
SLIDE 43

ICE #10

  • Exercise 1

Create a 1 x 5 vector A with all elements equal to 0

  • Exercise 2

Create a 3 x 1 vector B with all elements equal to 1

  • Exercise 3

Create a 1 x 5 vector C with elements equal to 1, 2, 3, 4, π respectively.

  • Exercise 4

Create 1-row vector D with element’s from 3 to 27 with step 3 by using the appropriate operator

  • Exercise 5

Create a 3 x 3 matrix E with elements with random values.

  • Exercise 6

Create the following matrix

43

slide-44
SLIDE 44

ICE #10

  • Exercise 7

Check the size of F

  • Exercise 8

Create the following Matrix 1. find the transpose of G 2. print on display the element G13 of the transpose of G 3. print on display the second row of the transpose of G 4. print on display the third column of the transpose of G 5. find the determinant of G

44

slide-45
SLIDE 45

ICE #10

  • Exercise 9

Create the following Matrices 1. Find the Matrix H+J 2. Find the Matrix H * J 3. Multiply H by J, element-by-element 4. Find indexes of all elements of J that are equal to 2. Do this in one command.

  • Exercise 10

Solve the linear system of equations ax=b if

45

slide-46
SLIDE 46

ICE #10

  • Exercise 11
  • Create two vectors v1 = [2 5 10] v2 = [-5 -2 2]
  • Compute dot product
  • Compute cross product
  • Can you tell if vectors are orthogonal?
  • Can you tell if vectors are parallel?

46

slide-47
SLIDE 47

Programming: Scripts and Functions

  • MATLAB is at its best when used as a programming language. It’s nice to be able to throw in a

couple of matrices and see what happens, but typically we want to use MATLAB to solve more complicated problems, involving several methodical steps of calculations. For such problems, it is best to write a script or a function - that is: a program.

  • Although both scripts and functions are simply named sequence of commands, it is important to

note the differences between these two concepts:

47

Script Function Has access to and uses all variables from the MATLAB session. Has access to only the variables passed as arguments. Gives the MATLAB session access to all variables it creates. Gives the MATLAB session access to only the variables it returns. Just a sequence of ordinary MATLAB commands. Contains one extra line describing input and output

slide-48
SLIDE 48

Scripts

  • In its simplest form, a script is simply a list of MATLAB commands that should be executed
  • sequentially. A script should be stored in a file. For example, a simple script to plot a sine function

follows:

x=-pi:.1:pi; y=sin(x); plot(x,y)

  • If you intended to run this often you could use either your favorite text editor or MATLAB built-in

text editor one to type these commands into a file called “plotsine.m”. After that, to see the plot

  • f the sine function inside MATLAB you would need only to type

>> plotsine

  • It is worth emphasizing that MATLAB calls its programs by file name. What ever the name of the

file, it must end in “.m” – that is how MATLAB recognizes it. To run the program, you type the name without the “.m” in the command line. This is true for both functions and scripts.

  • The above approach works if you save your script in your working directory (which is

recommended). However, you can also run scripts stored at any other location by using command run(scriptname), where scriptname is either relative or absolute path to your script file including file extension.

48

slide-49
SLIDE 49

Flow Control

  • More often, scripts are used to automate and abbreviate repetitive
  • work. For that reason we typically use the flow control statements.

Flow control statements designed to alter the flow of execution; either to perform a sequence of commands for each element from a list of parameters, or to change actions based on a condition.

  • Certain flow control structures have become standard for all

computer languages (recall "if" and "for" statements from bash scripts in Linux), and MATLAB supports these.

  • Comprehensive list of flow control commands could be found here

https://www.mathworks.com/help/matlab/control-flow.html

49

slide-50
SLIDE 50

Flow Control: Conditionals

  • In all flow control we need to make decisions: to continue or not; to take one action or another. In other words we must constantly perform

logical tests.

  • To manage logical conditions for such tests the logical data type is used.

>> x = -1; >> x < 0 ans = logical 1

  • One must be able to evaluate complicated logical expressions for a number of mathematical tasks. MATLAB, like all programming languages,

provides a full ensemble of logical operators for that purpose.

50

slide-51
SLIDE 51

Flow Control: Conditionals

  • Here are some examples:

>> a=-1; b=1; c=0; >> c==0 ans = 1 >> c==a ans = 0 >> a < b ans = 1 >> a >=c ans = 0 >> a < b && a <=c ans = 0 >> a < b || a <= c ans = 1 >> a < b || (a<=c && b<c) ans = 1 >> (a<b || a>=c) && b<c ans = 0

51

slide-52
SLIDE 52

Flow Control: Conditionals

  • Actual flow control construct allowing to execute different sets of commands based on logical tests is the “if”

construct (if some condition is true, then do one set of things; if not, then perhaps do something else, or skip the actions).

  • The syntax for “if” construct in MATLAB looks like this:

if <condition_0> Commands to be executed if <condition_0> is true elseif <condition_1> Commands to be executed if <condition_1> is true … elseif <condition_N> Commands to be executed if <condition_N> is true else Commands to be executed if non of the <condition_0>, … , <condition_N> is true end

  • The else and elseif statements are optional. If it suits your code, the construction could be as simple as

if <condition> Commands to be executed if <condition> is true end

52

slide-53
SLIDE 53

Flow Control: Conditionals

  • Here is an example (we assume that variable x was defined outside the script):

minVal = 2; maxVal = 6; if (x >= minVal) && (x <= maxVal) disp('Value within specified range.') elseif (x > maxVal) disp('Value exceeds maximum value.') else disp('Value is below minimum value.’) end

  • Simplified case (we assume that variable len was defined outside the script):

if (len < 0) disp(‘ERROR: Length could not be negative.’) end

53

slide-54
SLIDE 54

Flow Control: “for” Loop

  • If you want to perform some operation a specific number of times then you should use a “for” construction.

In MATLAB, the for loop has the form

for <variable>=<list> Commands to be executed (commands probably will use <variable>) end

  • Here is an example that computes the factorial fact of a number K.

fact = 1; for i=2:K fact = fact*i; end

  • This kind of construction is standard. Some variable is “initialized”; a value is put into it to start the

sequential calculations. Then the for loop is started. The line that does this specifies a parameter name (<variable>), and the collection of values (<list>) it will be chosen from. It is said that “the variable is iterated over the list”.

  • In the example above, the parameter i will have a value of 2 at the beginning of the for loop. Then the

variable fact will be assigned the number given by its old value multiplied by 2. The loop continues by moving to the next value in the list – in this case 3. Thus, if K = 5 then we see that the above example would be exactly equivalent to the MATLAB commands below.

fact= 1; fact = 1*2; fact = 2*3; fact = 6*4; fact = 24*5;

54

slide-55
SLIDE 55

Flow Control: “while” Loop

  • If you need to perform some operation an unknown number of times, until some

condition is satisfied, then you should use a “while” construction. The syntax is as follows:

while <condition> Commands to be executed while <condition> is true end

  • Here is an example in which we find the largest power n of 2 that is less than or

equal to a given positive number K.

n = 0; while 2^n <= K n = n+1; end % 2^n is now greater than K, so reduce it. n = n-1;

55

slide-56
SLIDE 56

Flow Control: “while” Loop

  • As with the for loop, we initialize the parameter n (to 0). Then we test a criterion: if 2n

≤ K then we continue by incrementing n. We go around and test again: is 2n ≤ K? If so, we continue. Indeed we continue until 2n > K, after which n is too large, so we reduce it by one. Thus we see that if K = 13 then the value we want for n is 3, inasmuch as 23 ≤ 13 and 24 > 13. This loop would be exactly equivalent to the following MATLAB statements.

n = 0; n = 1; n = 2; n = 3; n = 4; n = 3;

  • It is worth stressing the difference in usage between this and “for”. Use a “for” loop

when you know ahead of time exactly the set of parameters over which you will iterate; but use a “while” loop when you need to do it until some criterion becomes false.

56

slide-57
SLIDE 57

ICE #11

  • Create a script called bisec.m that will implement

Bisection Method (https://en.wikipedia.org/wiki/Bisection_method or http://mathworld.wolfram.com/Bisection.html).

  • The method can be described with this flow diagram
  • n the right.
  • You can use fzero command to check your results
  • For example:

>> fun = @(x) x^2+2*x-3; % define function >> x0 = [0 5]; % initial interval >> x = fzero(fun, x0) % solve x = 1.0000

57

slide-58
SLIDE 58

Functions

  • Sometimes we want to use a script as part of a larger computation – we want it to manipulate a

couple of arguments and return a value that we will use for further work. When that is the aim, we usually write a function instead of a simple script. Basically, a script is just a shortcut for a MATLAB session, saving us some typing.

  • A function is a self-contained program that can be reused from one session to another, or even

called from other scripts and functions. All scripts and functions for MATLAB have file names that end in “.m”.

  • Since scripts and functions are really quite similar, we need only two lines to change a script into

a function. The first one tells what variables in the script are to be passed as arguments, and what variables are to be returned to the calling program. The second one simply denotes where lines of code corresponding to a particular function end

function [return1,return2,…,returnM]=functionname(arg1,arg2,…,argN) Commands to be executed when function is called (body of the function). The commands will probably use arg1,…,argN and set values for return1,…,returnM. end

  • You may have any number of arguments, and any number of returned variables. The returned

variables must all have the same dimension. The function name can be anything you pick except a name that has already been used by MATLAB – do not try to name your function “sin”.

58

slide-59
SLIDE 59

Functions

  • For example, consider a function that takes two vectors and computes their dot product.

function prod=innerproduct(v1,v2) if size(v1)==size(v2), v1 = v1(:); v2 = v2(:); prod = v1’*v2; else error(’The vector inputs must be the same size’); end end \% ends the function

  • Note that this should be saved in a file called “innerproduct.m”. The name of the file in which a

function is stored should always be the same as the name of the function.

  • Since the vectors v1 and v2 are not returned from the function, we can change them in any way

we like inside the function without worrying that we will mess up work in the calling program. In many programming languages this is referred as “arguments are passed by value”. Thus we feel free to be sure that both vectors are column vectors before we try to compute their inner product.

59

slide-60
SLIDE 60

Functions

  • We would call this function from a MATLAB session or another MATLAB script simply by

creating vectors by any name but with the same dimension, and then calling innerproduct(). For example, to compute the mutual dot products of three vectors, consider the following.

>> x=ones(1,10); >> y=1:10; >> z=22:2:40; >> p1 = innerproduct(x,y) p1 = 55 >> p2 = innerproduct(x,z) p2 = 310 >> p3 = innerproduct(y,z) p3 = 1870

60

slide-61
SLIDE 61

Functions

  • As mentioned, you can call other functions while defining your own function.

These could be either built-in functions or your own functions.

  • If there is a piece of code that you use repeatedly in your function itself but it’s

unlikely that you may need this code anywhere else, you can extract this code into another function and place it in the same file. This function should be placed after your “main” function and may be visible only inside this file/function. Such functions are called local functions and were introduced in MATLAB R2016b. Also note that local functions may be also used in scripts.

  • You also can call function you are defining inside the definition of this function.

This technic is know as recursion.

  • Note that there is a certain threshold of how many nesting recursive calls you

may have in MATLAB. By default value is 500. You can change it by set(0, 'RecursionLimit’, <lilmit>). But it is better to avoid such a deep recursion.

61

slide-62
SLIDE 62

Functions

  • Here is an example that illustrates all the technics described in the previous slide. The function computes

factorial of a given number and the following content is stored in a single file called factorial.m:

function fact=factorial(n) if ~isinteger(n) raiseinputerror('parameter must be an integer.') elseif n<0 raiseinputerror('parameter must be a positive number.') elseif n==1 fact=1; else fact=n*factorial(n-1); % recursive call end end function raiseinputerror(msg) % local function error(['Invalid input: ' msg]) % calling built-in function end

62

slide-63
SLIDE 63

Functions

  • As mentioned function can have multiple return parameters. Here is an example
  • f the function that returns the mean and standard deviation of an input vector.

function [m,s] = stat(x) n = length(x); m = sum(x)/n; s = sqrt(sum((x-m).^2/n)); end

  • Once again, to call such function you also need to use square brackets while

defining variable where you want the result to be stored.

>> values = [12.7, 45.4, 98.9, 26.6, 53.1]; >> [ave,stdev] = stat(values) ave = 47.3400 stdev = 29.4124

63

slide-64
SLIDE 64

Functions

  • You can use return statement to stop function execution and return control to calling function:

function fact=factorial(n) if ~isinteger(n) disp(‘ERROR: parameter must be an integer.’) % do not interrupt function return end …

  • You can use built-in function error(message) to display error message (message) and also

immediately stop function execution:

function fact=factorial(n) if ~isinteger(n) error('parameter must be an integer.’) % interrupts function end

  • Check out this page for more information on functions

https://www.mathworks.com/help/matlab/functions.html

64

slide-65
SLIDE 65

Importing/Exporting Data

  • You can import data to MATLAB session using importdata function. For example,

filename = 'myfile01.csv'; delimiterIn = ‘,'; headerlinesIn = 1; someData = importdata(filename,delimiterIn,headerlinesIn);

  • The above code imports CSV file called myfile01.csv. The delimiter is defined by the second parameter
  • delimiterIn. headerlinesIn tells MATLAB to ignore the first line since it contains names of the

columns but not the data itself.

  • To write modified data stored in someData matrix variable to a delimited file you can use the following

command:

dlmwrite(‘newfile01.csv’, someData, ’,’)

  • Note that dlmwrite will truncate all fractional parts by default. To specify desired precision use

dlmwrite(‘newfile01.csv', someData, 'delimiter’,’ ,','precision',3)

  • There is a bunch of input files formats that MATLAB supports. You can find the complete list here

https://www.mathworks.com/help/matlab/import_export/supported-file-formats.html

  • There is also a bunch of other ways to import/exoprt data. See more here:

https://www.mathworks.com/help/matlab/data-import-and-export.html

65

slide-66
SLIDE 66

Text Output and Formatting

  • By default MATLAB displays result of every command unless you add semicolon

after at the end of the command.

  • To change the way how MATLAB outputs numerical values in the current session

use format comman: https://www.mathworks.com/help/matlab/ref/format.html

  • Use disp to display the result. Use sprintf to create text, and then display it

with disp. Use fprintf to directly display the text without creating a variable: https://www.mathworks.com/help/matlab/ref/disp.html https://www.mathworks.com/help/matlab/ref/fprintf.html https://www.mathworks.com/help/matlab/ref/sprintf.html https://www.mathworks.com/help/matlab/ref/num2str.html

  • See also http://www.math.wsu.edu/math/kcooper/M300/matlabtextoutput.php

https://www.mathworks.com/help/matlab/matlab_prog/formatting-strings.html

66

slide-67
SLIDE 67

Plots

  • Plot 2-D with plot command

https://www.mathworks.com/help/matlab/ref/plot.html

  • Plot 3-D with mesh command

https://www.mathworks.com/help/matlab/ref/mesh.html

  • Create grid with ndgrid command

https://www.mathworks.com/help/matlab/ref/ndgrid.html

  • There is a lot of other ways do visualize data!

https://www.mathworks.com/help/matlab/creating_plots/types-of- matlab-plots.html

67

slide-68
SLIDE 68

ICE #12

  • Recall that we can approximate the derivative of a function f at a point x using on of the formulas:

f'(x) ~ Fh = (f(x+h)-f(x)) / (h) or f'(x) ~ Fh = (f(x+h)-f(x-h)) / (2h).

  • For this exercise, you must write two functions deriv_test1 and deriv_test2 that both take three

arguments: the function f, the point x where the derivative is to be approximated x, and the correct value of the derivative. Thus, the function will be called as deriv_test1(f,x,correct) or deriv_test2(f,x,correct).

  • The functions will compute the derivative approximation using the above formulas values of h going down in

powers of ten, with exponent p, from 10-1 to 10-16. It will plot the absolute error |f'(x)-Fh|for each of those values of p = -1, -2, ..., -16. In other words, the power p of 10 is on the horizontal axis, and the error is on the vertical axis.

  • For every given precision function must output intermediate results: approximated value and error.
  • The function must return the vector of approximations to the derivative.
  • You can calculate “correct” value using this approach

https://www.mathworks.com/help/symbolic/differentiation.html

  • Optionally you can create a function plot_error that takes array of error values as an input parameter

and plots them adding title and axes labels. You can then use in both deriv_test1 and deriv_test2.

  • Create a script called run_deriv.m that will execute deriv_test1 and deriv_test2 for some function

and plot computational errors for the both functions on the same graph.

68

slide-69
SLIDE 69

Polymomials

  • MATLAB represents polynomials with numeric vectors containing the polynomial coefficients
  • rdered by descending power. For example, [1 -4 4] corresponds to x2 - 4x + 4.
  • polyval(p,x) - evaluates polynomial p at the given point x.
  • polyvalM(p,X) - evaluates matrix polynomial p at the given point x.
  • conv(p, q) - multiplies polynomials p and q.
  • deconv(p, q) - divides polynomial p by q.
  • roots(p) - returns roots of the polynomial p.
  • polyfit(x,y,n) - returns the coefficients for a polynomial p of degree n that is a best fit (in

a least-squares sense) for the data in y.

  • polyder(p) - returns derivative of the polynomial p.
  • polyint(p) - returns anti-derivative of the polynomial p.
  • Check out this link for more: https://www.mathworks.com/help/matlab/polynomials.html

69

slide-70
SLIDE 70

Other Math Functions

  • Take a look at this list:

https://www.mathworks.com/help/matlab/functionlist.html#mathe matics

70

slide-71
SLIDE 71

MATLAB Symbolics

  • MATLAB also has some features to do symbolic computations. These

are implemented in “Symbolic Math Toolbox” which is included by default in the Student’s Version.

  • See the book by Prof. Cooper.
  • See https://www.mathworks.com/help/symbolic/

72

slide-72
SLIDE 72

References

  • MATLAB Documentation by MathWorks

(https://www.mathworks.com/help/index.html)

  • Essentials of Scientific Computing by Prof Cooper

(http://millenniummath.org/Computation/scientific_computing.pdf)

  • Matlab: A Practical Introduction to Programming and Problem Solving

by Stormy Attaway, Butterworth-Heinemann, 3rd edition, 2013.

73