MATLAB
1
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
1
solve algebraic and differential equations, can integrate and differentiate symbolic expressions, and can simplify and manipulate algebraic expressions.
The syntax for this package is relatively intuitive for mathematicians. It has relatively powerful typesetting capabilities.
typesetting abilities.
for many platforms. Unfortunately, it suffers from perhaps the most obscure syntax of any package of its kind, and has relatively poor graphics.
they are best when programmed to run complicated algorithms. They can handle all problems involving numerical matrices and vectors.
package for both mathematicians and engineers. For a price, it can have some symbolic capability.
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.
Matlab.
changing a parameter and running a sequence of calculations anew.
2
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.
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.
uses a symbolic engine called MuPAD, allowing access to symbolic computing abilities.
3
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
arithmetic operations with a very natural syntax. Second, Matlab requires that every computation be assigned to a variable.
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
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
We may view the contents of the variable seven at any time simply by typing its name:
>> seven seven = 7
could define a variable called ten by
>> ten=seven+3 ten = 10
to denote exponentiation:
>> myvariable=2*(ten-2)+(ten/5)^2 myvariable = 20 5
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.
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
just shows the names of the variables)
(this shows more information on the variables, similar to what is in the Workspace Window)
(note: separate the names with spaces)
command one should add semicolon at the end of this command.
7
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.
is inferred automatically and you may not specify it explicitly.
following syntax variablename = typename(variablevalue)
class(variablename)command.
8
numbers and provide more efficient use of memory.
such as ischar or isfloat. See this link for more: https://www.mathworks.com/help/matlab/data-type- identification.html
types.html.
9
everything in MATLAB is written to work with vectors and matrices.
same type. A matrix can be visualized as a table of values. The dimensions
columns.
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
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
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
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
brackets, separated by semicolons (rather than commas or spaces):
>> c = [1; 2; 3; 4] c = 1 2 3 4
any row vector created using any method can be transposed to result in a column
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
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
>> v(5) ans = 9
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
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
element from the preceding vector b to now store the value 11 instead of 9:
>> b(2) = 11 b = 7 3 11
a gap between the current vector and the element being added, MATLAB will fill in with zeros.
13
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
which there are different numbers of values in the rows, the result will be an error message.
>> mat = [2:4; 3:5] mat = 2 3 4 3 4 5
14
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
>> mat(1:2,2:3) ans = 3 4 4 5
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
15
>> evec = [] evec = []
takes what is currently in evec, which is nothing, and adds a 4 and 7 to it.
>> evec = [evec 4 7] evec = 4 7
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
>> mat(:,2) = []
16
>> mat = [2:4; 3:5]; >> mat(1,2) = 11 mat = 2 11 4 3 4 5
entire second row with values from a vector obtained using the colon operator:
>> mat(2,:) = 5:7 mat = 2 11 4 5 6 7
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
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
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
vectors and matrices.
>> vec = -2:1 vec =
>> length(vec) ans = 4
matrix.
>> size(vec) ans = 1 4
19
(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
>> A = ones(2,3) A = 1 1 1 1 1 1
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
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
(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
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
same, but their meaning is changed to that appropriate for matrix operations.
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
>> m/2
every element of the matrix:
>> (m+3)-5 m = 7 19 4 1
by a scalar (or dividing every element in a vector or a matrix by a scalar).
22
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
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 ^
be used.
>> v = [3 7 2 1]; >> v ^ 2 ans = 9 49 4 1
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
24
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
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
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
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
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
>> cross(v1, v2) ans =
27
algebra.html
28
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
used on the resulting vector isg:
>> sum(isg) ans = 3
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
elements in a vector that are greater than 5:
>> vec = [5 3 6 7 2]; >> find(vec > 5) ans = 3 4
specified criteria. For example:
>> A = [5 6 7 8; 9 7 5 3]; >> find(A == 5) ans = 1 6
>> 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
return logical 0, whereas using the equality operator will result in an error message.
30
in a usual way:
>> x = pi/6 x = 0.5236 >> sin(x) ans = 0.5000
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
https://www.mathworks.com/help/matlab/trigonometry.html and https://www.mathworks.com/help/matlab/exponents-and-logarithms.html
31
numbers as an approximation so as to support a trade-off between range and
base; the base for the scaling is normally two, ten, or sixteen. A number that can be represented exactly is of the following form:
exponent is also an integer. For example:
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
the variable. MATLAB supports two possible precisions: single and double.
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).
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).
https://www.mathworks.com/help/matlab/matlab_prog/floating-point-numbers.html
http://www.math.wsu.edu/math/kcooper/M300/matlabfloat.php
33
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
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.
https://www.mathworks.com/help/matlab/ref/reshape.html
34
>> e = exp(1) e = 2.7183
>> 1 / 0 ans = Inf >> (+Inf)+(-Inf) ans = NaN
eps('single') and eps('double').
>> eps('double') ans = 2.2204e-16
35
pieces of text as character vectors, such as c = 'Hello World’.
and ‘o’.
>> chr = 'Hello, world' chr = 'Hello, world’
change them.
>> chr(8:12) ans = 'world' >> chr(1:5) = 'HELLO' chr = 'HELLO, world'
vectors.
>> street = '123 Maple St.'; >> city = 'Lakeview, MA 01234'; >> fullAddress = [street ', ' city] fullAddress = '123 Maple St., Lakeview, MA 01234'
36
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
character arrays, but add codes of correspodning characters elementwise.
'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
Starting in MATLAB R2017a, you can create strings using double quotes.
>> str = "Welcome, friend" str = "Welcome, friend“
>> chr = 'Hello, world'; >> str = string(chr) str = "Hello, world“
different size.
>> str = ["Mercury","Gemini","Apollo"; "Skylab","Skylab B","ISS"] str = 2×3 string array "Mercury" "Gemini" "Apollo" "Skylab" "Skylab B" "ISS"
single character:
>> str(1, 1) + " and " + str(1, 2) ans = "Mercury and Gemini“
38
(function_handle can have broader use, but we will see it later).
whose data type is function_handle. Anonymous functions can accept inputs and return outputs. They can contain only a single executable statement.
>> sqr = @(x) x.^2 sqr = function_handle with value: @(x)x.^2
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.
standard function.
>> sqr(25) ans = 625
39
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);
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);
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;
affect parabola.
40
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));
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));
g(2) ans = 2.3333
41
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
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
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
Create a 1 x 5 vector A with all elements equal to 0
Create a 3 x 1 vector B with all elements equal to 1
Create a 1 x 5 vector C with elements equal to 1, 2, 3, 4, π respectively.
Create 1-row vector D with element’s from 3 to 27 with step 3 by using the appropriate operator
Create a 3 x 3 matrix E with elements with random values.
Create the following matrix
43
Check the size of F
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
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.
Solve the linear system of equations ax=b if
45
46
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.
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
follows:
x=-pi:.1:pi; y=sin(x); plot(x,y)
text editor one to type these commands into a file called “plotsine.m”. After that, to see the plot
>> plotsine
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.
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
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.
computer languages (recall "if" and "for" statements from bash scripts in Linux), and MATLAB supports these.
https://www.mathworks.com/help/matlab/control-flow.html
49
logical tests.
>> x = -1; >> x < 0 ans = logical 1
provides a full ensemble of logical operators for that purpose.
50
>> 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
construct (if some condition is true, then do one set of things; if not, then perhaps do something else, or skip the actions).
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
if <condition> Commands to be executed if <condition> is true end
52
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
if (len < 0) disp(‘ERROR: Length could not be negative.’) end
53
In MATLAB, the for loop has the form
for <variable>=<list> Commands to be executed (commands probably will use <variable>) end
fact = 1; for i=2:K fact = fact*i; end
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”.
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
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
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
≤ 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;
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
Bisection Method (https://en.wikipedia.org/wiki/Bisection_method or http://mathworld.wolfram.com/Bisection.html).
>> fun = @(x) x^2+2*x-3; % define function >> x0 = [0 5]; % initial interval >> x = fzero(fun, x0) % solve x = 1.0000
57
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.
called from other scripts and functions. All scripts and functions for MATLAB have file names that end in “.m”.
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
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
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
function is stored should always be the same as the name of the function.
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
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
These could be either built-in functions or your own functions.
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.
This technic is know as recursion.
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
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
function [m,s] = stat(x) n = length(x); m = sum(x)/n; s = sqrt(sum((x-m).^2/n)); end
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
function fact=factorial(n) if ~isinteger(n) disp(‘ERROR: parameter must be an integer.’) % do not interrupt function return end …
immediately stop function execution:
function fact=factorial(n) if ~isinteger(n) error('parameter must be an integer.’) % interrupts function end
https://www.mathworks.com/help/matlab/functions.html
64
filename = 'myfile01.csv'; delimiterIn = ‘,'; headerlinesIn = 1; someData = importdata(filename,delimiterIn,headerlinesIn);
columns but not the data itself.
command:
dlmwrite(‘newfile01.csv’, someData, ’,’)
dlmwrite(‘newfile01.csv', someData, 'delimiter’,’ ,','precision',3)
https://www.mathworks.com/help/matlab/import_export/supported-file-formats.html
https://www.mathworks.com/help/matlab/data-import-and-export.html
65
after at the end of the command.
use format comman: https://www.mathworks.com/help/matlab/ref/format.html
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
https://www.mathworks.com/help/matlab/matlab_prog/formatting-strings.html
66
https://www.mathworks.com/help/matlab/ref/plot.html
https://www.mathworks.com/help/matlab/ref/mesh.html
https://www.mathworks.com/help/matlab/ref/ndgrid.html
https://www.mathworks.com/help/matlab/creating_plots/types-of- matlab-plots.html
67
f'(x) ~ Fh = (f(x+h)-f(x)) / (h) or f'(x) ~ Fh = (f(x+h)-f(x-h)) / (2h).
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).
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.
https://www.mathworks.com/help/symbolic/differentiation.html
and plots them adding title and axes labels. You can then use in both deriv_test1 and deriv_test2.
and plot computational errors for the both functions on the same graph.
68
a least-squares sense) for the data in y.
69
https://www.mathworks.com/help/matlab/functionlist.html#mathe matics
70
are implemented in “Symbolic Math Toolbox” which is included by default in the Student’s Version.
72
(https://www.mathworks.com/help/index.html)
(http://millenniummath.org/Computation/scientific_computing.pdf)
by Stormy Attaway, Butterworth-Heinemann, 3rd edition, 2013.
73