Lecture - Note3 - Introduction To MATLAB
Lecture - Note3 - Introduction To MATLAB
Introduction to MATLAB
This chapter presents features and capabilities of MATLAB pertinent to numerical meth-
ods. These range from vector and matrix operations and symbolic calculations to plot-
ting options for functions and sets of data. Several MATLAB built-in functions and their
applications will also be introduced. The chapter concludes with guidelines to prepare
user-defined functions and script files to perform specific tasks.
ans =
1.6180
The outcome of a calculation can be stored under a variable name, and suppressed by
using a semicolon at the end of the statement:
If the variable is denoted by “a”, other elementary functions include abs(a) for |a|,
sin(a) for sin(a), log(a) for ln a, log10(a) for log10(a), exp(a) for ea, and many more.
Descriptions of these functions are available through the help command.
TABLE 2.2
MATLAB Relational Operators
Mathematical Symbol MATLAB Symbol
= ==
≠ ∼=
< <
> >
≤ <=
≥ >=
AND & or &&
OR | or ||
NOT ∼
TABLE 2.3
MATLAB Format Options
Format Option Description Example: 73/7
format short (default) Fixed point with 4 decimal digits 10.4286
format long Fixed point with 14 decimal digits 10.428571428571429
format short e Scientific notation with 4 decimal digits 1.0429e+001
format long e Scientific notation with 14 decimal digits 1.042857142857143e+001
format bank Fixed point with 2 decimal digits 10.43
2.2 Vectors and Matrices
Vectors can be created in several ways in MATLAB. The row vector v = [1 4 6 7 10 ]
is created as
>> v = [1 4 6 7 10]
v =
1 4 6 7 10
Commas may be used instead of spaces between elements. For column vectors, the ele-
ments must be separated by semicolons.
>> v = [1;4;6;7;10]
v =
1
4
6
7
10
The size of a vector is determined by the size command. For the last (column) vector
defined above, we find
>> size(v)
ans =
5 1
Arrays of numbers with equal spacing can be created more effectively. For example, a
row vector whose first element is 2, its last element is 17, with a spacing of 3 is created as
>> v = [2:3:17] or >> v = 2:3:17
v =
2 5 8 11 14 17
v =
2
5
8
11
14
17
Any component of a vector can be easily retrieved. For example, the third component of
the above vector is retrieved by typing
>> v(3)
ans =
8
A group of components may be retrieved as well. For example, the last three components
of the row vector defined earlier are recovered as
>> v = 2:3:17;
>> v(end−2:end)
ans =
11 14 17
2.2.1 Linspace
Another way to create vectors with equally spaced elements is by using the linspace
command.
x =
1.0000 1.8000 2.6000 3.4000 4.2000 5.0000
The default value for the number of points is 100. Therefore, if we use x = linspace(1,5),
then 100 equally spaced points will be generated between 1 and 5.
2.2.2 Matrices
A matrix can be created by using brackets enclosing all of its elements, rows separated by
a semicolon.
A =
1 −2 3
−3 0 1
5 1 4
An entry can be accessed by using the row and column number of the location of that
entry.
>> A(3,2) % Entry at the intersection of the 3rd row and 2nd column
ans =
Row_2 =
−3 0 1
Col_3 =
3
1
4
>> v = [1;0;1];
>> A_new = A; % Pre-allocate the new matrix
>> A_new(:,2) = v % Replace the 2nd column with v
A_new =
1 1 3
−3 0 1
5 1 4
The m × n zero matrix is created by using zeros(m,n); for instance, the 3 × 2 zero
matrix:
>> A = zeros(3,2)
A =
0 0
0 0
0 0
The m × n zero matrix is commonly used for pre-allocation of matrices to save mem-
ory space. In the matrix A defined above, any entry can be altered while others remain
unchanged.
>> A(2,1) = −3; A(3,2) = −1
A =
0 0
−3 0
0 −1
>> size(A)
ans =
3 2
The n × n identity matrix is created by eye(n):
>> I = eye(3)
I =
1 0 0
0 1 0
0 0 1
Matrix operations (Section 1.2) can be easily performed in MATLAB. If the sizes are not
compatible, or the operations are not defined, MATLAB returns an error message to that
effect.
C =
3 5
−6 4
−4 12
ans =
16
>> At = A.'
At =
1 0 1
2 2 2
−3 1 5
>> Ai = inv(A)
Ai =
>> help \
The backslash (\) operator is employed for solving a linear system of algebraic equations
Ax = b, whose solution vector is obtained as x = A−1b. However, instead of performing
x=inv(A)*b, it is most efficient to find it as follows:
x =
1
3
2
>> help /
TABLE 2.4
Element-by-Element Operations
MATLAB Symbol Description
.* Multiplication
./ (right) Division
.^ Exponentiation
For example, suppose we want to raise each element of a vector to power of 2.
>> x = 0:2:10
x =
0 2 4 6 8 10
ans =
0 4 16 36 64 100
Now consider (1 + x)/(2 + x) where vector x is as defined above. This fraction is to be evalu-
ated for each value of x:
>> (1.+x)./(2.+x)
ans =
If two arrays are involved in the element-by-element operation, they must be of the same
size.
>> v = [1;2;3];
>> w = [2;3;4];
>> v.*w
ans =
2
6
12
A =
−1 0 1 3
1 2 1 −4
0 2 4 1
1 0 −2 5
−1
2
4
5
>> D = diag(diag(A)) % Constructs a diagonal matrix with diagonal entries of A
D =
−1 0 0 0
0 2 0 0
0 0 4 0
0 0 0 5
The command diag(A,1) creates a vector consisting of the entries of A that are one
level higher than the main diagonal. Of course, the dimension of this vector is one less
than the dimension of A itself. Then diag(diag(A,1),1) creates a matrix (size of A)
whose entries one level higher than the main diagonal are the components of the vector
diag(A,1).
>> diag(A,1)
ans =
0
1
1
>> diag(diag(A,1),1)
ans =
0 0 0 0
0 0 1 0
0 0 0 1
0 0 0 0
Similarly, diag(A,−1) creates a vector whose components are the entries of A that are one
level lower than the main diagonal. Subsequently, diag(diag(A,−1),−1) generates a
matrix (size of A) whose entries one level lower than the main diagonal are the components
of the vector diag(A,−1).
>> diag(A,−1)
ans =
1
2
−2
>> diag(diag(A,−1),−1)
ans =
0 0 0 0
1 0 0 0
0 2 0 0
0 0 −2 0
Other commands such as diag(A,2), diag(A,−2), and so on can be used for simi-
lar purposes. The command triu(A) returns the upper-triangular version of A, that is,
matrix A with all entries below the main diagonal set to zero.
>> triu(A)
ans =
−1 0 1 3
0 2 1 −4
0 0 4 1
0 0 0 5
Similarly, tril(A) returns the lower-triangular version of A, that is, matrix A with all
entries above the main diagonal set to zero.
>> tril(A)
ans =
−1 0 0 0
1 2 0 0
0 2 4 0
1 0 −2 5
>> syms a b
>> c = 2.1;
>> g = 4.81*sin(a/3)+3*exp(−b/c)
g =
In symbolic expressions, numbers are always converted to the ratio of two integers, as it
is observed here as well. For decimal representation of numbers, we use the vpa (variable
precision arithmetic) command. The syntax is
>> vpa(g,n)
where n is the number of desired digits. For example, if four digits are desired in our cur-
rent example, then
>> g4 = vpa(4.81*sin(a/3)+3*exp(−b/c),4)
g4 =
4.81*sin(0.3333*a) + 3.0/exp(0.4762*b)
To evaluate the symbolic function g for specified values of a and b, we use the subs
command which replaces all variables in the symbolic expression g with values obtained
from the MATLAB workspace. For instance, to evaluate g when a=1 and b=2,
>> a = 1; b = 2; subs(g)
ans =
3*exp(−20/21) + (481*sin(1/3))/100
>> double(ans)
ans =
2.7313
The function g = 4.81 sin(a/3) + 3e−b/c in the current example may also be defined sym-
bolically via
>> g = sym('4.81*sin(a/3)+3*exp(−b/c)')
g =
4.81*sin(a/3) + 3*exp(−b/c)
Note that a, b, and c do not need to be declared symbols, as this is handled automati-
cally by sym in the definition of g. Also, assignment of a specific value (such as c=2.1) to
a variable will not be taken into account when using sym. Instead, we can use the subs
command at this stage:
g =
3*exp(−(10*b)/21) + 4.81*sin(a/3)
This agrees with what we saw at the outset of this discussion. The symbolic function g
can be evaluated for a list of specific parameter values as follows:
>> a = 1; b = 2; double(subs(g))
ans =
My_function = @(arguments)(expression)
As an example, let us create an anonymous function (in the Command Window) to eval-
uate R = 1 + e − bx/2 when b = 1 and x = 2.
>> R = @(b,x)(sqrt(1+exp(−b*x/2)));
This creates R(b,x), which is then evaluated for specific values of b and x. For example,
>> R(1,2)
ans =
1.1696
>> R = @(b,x)(sqrt(1+exp(−b*x/2)));
>> L = @(b,x)(log(R(b,x)));
>> L(1,2)
ans =
0.1566
>> syms b x
>> R = matlabFunction(sqrt(1+exp(−b*x/2)))
R =
>> R(1,2)
ans =
1.1696
As expected, this agrees with the earlier result using the anonymous function. Note that
if the desired order of variables is not specified by the user, MATLAB will list them in
alphabetical order. In the above example, omitting the list of variables would still result in
R(b,x). If, however, R(x,b) is desired, the 'vars' option is utilized as follows:
R =
@(x,b)sqrt(exp(b.*x.*(−1.0./2.0))+1.0)
In the previous example, where the function was defined as R(b,x), suppose b is a
scalar and x is a vector. Let b = 1 and x = [1 2 3]. Then,
>> b = 1; x = [1 2 3];
>> R(b,x)
ans =
Three outputs are returned, one for each component in the vector x. Note that, since the
second component of x happens to be 2, the second returned output matches what we got
earlier for the case of b = 1 and x = 2.
2.3.3 Differentiation
In order to find the derivative of a function with respect to any of its variables, the function
must be defined symbolically. For example, consider f(t) = t3−sin t, a function of a single
variable. To determine df/dt, we proceed as follows:
>> f = sym('t^3-sin(t)');
>> dfdt = diff(f)
dfdt =
3*t^2 - cos(t)
dfdt2 =
6*t + sin(t)
ans =
4.4570
>> h = sym('2*x+y^2');
>> hx = diff(h,'x')
hx =
>> hy = diff(h,'y')
hy =
2*y
To find the second partial derivative with respect to y, the diff command is applied to
the first partial:
>> hy2 = diff(hy,'y')
hy2 =
2.3.5 Integration
Indefinite and definite integrals are calculated symbolically via the int command.
∫
For example, the indefinite integral (2t + cos 3t) dt is calculated as
>> f = sym('2*t+cos(3*t)');
>> int(f)
ans =
sin(3*t)/3 + t^2
3
∫
The definite integral ( at − e t/2 ) dt, where a is a parameter, is calculated as follows:
1
>> g = sym('a*t-exp(t/2)');
>> syms t
>> I = int(g,t,1,3) % t is the integration variable, and 1 and 3 are limits of integration
I =
4*a - 2*exp(1/2)*(exp(1) - 1)
To evaluate the integral when a = 1, we proceed as follows:
>> a = 1; double(subs(I))
ans =
−1.665935599275873
Note that the default integration variable here is t. Thus, in the above example, it could
have been omitted to yield the correct result:
>> int(g,1,3)
ans =
4*a - 2*exp(1/2)*(exp(1) - 1)
for i = first:increment:last,
statements
end
The loop is executed as follows. The index i assumes its first value, all statements in the
subsequent lines are executed with i = first, then the program goes back to the for
command and i assumes the value i = first + increment and the process continues
until the very last run corresponding to i = last.
As an example, suppose we want to generate a 5 × 5 matrix A with diagonal
entries all equal to 1, and upper diagonal entries all equal to 2, while all other entries
are zero.
A = zeros(5,5); % Pre-allocate
for i = 1:5,
A(i,i) = 1; % Diagonal entries
end
for i = 1:4,
A(i,i+1) = 2; % Upper diagonal entries
end
Execution of this script returns
>> A
A =
1 2 0 0 0
0 1 2 0 0
0 0 1 2 0
0 0 0 1 2
0 0 0 0 1
if condition 1
set of expressions 1
else if condition 2
set of expressions 2
else
set of expressions 3
end
The simplest form of a conditional statement is the if/end structure. For example,
syms x
f = matlabFunction(log(x/3)); x = 1;
if f(x) ∼= 0,
error('x is not a root')
end
x is not a root
The if/else/end structure allows for choosing one group of expressions from two
groups. The most complete form of the conditional statement is the if/elseif/else/
end structure. Let us create the same 5 × 5 matrix A as above, this time employing the
if/elseif/else/end structure.
A = zeros(5,5);
for i = 1:5,
for j = 1:5,
if j == i+1,
A(i,j) = 2;
elseif j == i,
A(i,j) = 1;
end
end
end
Note that each for statement is accompanied by an end statement. Execution of this script
returns
>> A
A =
1 2 0 0 0
0 1 2 0 0
0 0 1 2 0
0 0 0 1 2
0 0 0 0 1
We will generate the same 5 × 5 matrix A as before, this time with the aid of the while loop.
A = eye(5); i = 1;
while i < 5,
A(i,i+1) = 2;
i = i+1;
end
A =
1 2 0 0 0
0 1 2 0 0
0 0 1 2 0
0 0 0 1 2
0 0 0 0 1
Formatted data may be better controlled via fprintf. Let us consider the script below.
A function f(x) = xcos x + 1 is defined. For k = 1, 2, 3, 4, 5 we want to calculate each c = ( 12 ) as
k
well as the corresponding function value f(c). The output is to be displayed in tabulated
form containing the values of k, c, and f(c) for each k = 1, 2, 3, 4, 5.
syms x
f = matlabFunction(x*cos(x)+1);
disp(' k c f(c)')
for k = 1:5,
c = (1/2)^k;
fc = f(c);
fprintf(' %2i %6.4f %6.4f\n',k,c,fc)
end
k c f(c)
1 0.5000 1.4388
2 0.2500 1.2422
3 0.1250 1.1240
4 0.0625 1.0624
5 0.0313 1.0312
The disp command simply displays all contents inside the single quotes. The fprintf
command is used inside for loop. For each k in the loop, fprintf writes the value of
k, the calculated value of c, as well as f(c). The format %2i means integer of length 2,
which is being used for displaying the value of k. In %6.4f, the letter f represents the
fixed-point format, 6 is the length, and the number 4 is the number of digits to the right of
the decimal. Finally, \n means new line. A more detailed description is available through
the help command.
>> y = dsolve('Dy+(x+1)*y=0','x')
y =
Note that the default independent variable in dsolve is t. Since in our example the
independent variable is x, we needed to specify that in single quotes. The initial-value
ɺɺ + 2xɺ + 2x = e − t , x(0) = 0, xɺ (0) = 1 is solved as
problem x
x =
The Figure Window can be used to edit the figure. These include adding grid, adjusting
thickness of lines and curves, adding text and legend, axes titles, and much more.
2.6.1 subplot
The built-in function subplot is designed to create multiple figures in tiled positions.
Suppose we want to plot the function z(x, t) = e−xsin(t + 2x) versus 0 ≤ x ≤ 5 for four values
of t = 0, 1, 2, 3. Let us generate the four plots and arrange them in a 2 × 2 formation.
x = linspace(0,5); t = 0:1:3;
for i = 1:4,
for j = 1:100,
z(j,i) = exp(-x(j))*sin(t(i)+2*x(j)); % Generate 100 values of z for each t
end
end
1.2
0.8
0.6
x
0.4
0.2
–0.2
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
t
FIGURE 2.1
Plot of a function versus its variable.
t=0 t=1
0.6 1.2
1
0.4 0.8
0.6
0.2
0.4
0 0.2
0
–0.2 –0.2
0 1 2 3 4 5 0 1 2 3 4 5
t=2 t=3
1 0.2
0.8 0.1
0.6 0
0.4 –0.1
0.2 –0.2
0 –0.3
–0.2 –0.4
–0.4 –0.5
0 1 2 3 4 5 0 1 2 3 4 5
FIGURE 2.2
Subplot in a 2 × 2 formation.
% Initiate Figure 2.2
subplot(2,2,1), plot(x,z(:,1)), title('t = 0')
subplot(2,2,2), plot(x,z(:,2)), title('t = 1')
subplot(2,2,3), plot(x,z(:,3)), title('t = 2')
subplot(2,2,4), plot(x,z(:,4)), title('t = 3')
>> x = sym('exp(-t)*(cos(t)+sin(t))');
>> ezplot(x,[0,5]) % Figure 2.1
>> y1 = sym('0.7*exp(−2*t/3)*sin(2*t)');
>> y2 = sym('exp(−t/3)*sin(3*t)');
>> ezplot(y1,[0,5]) % Initiate Figure 2.3
>> hold on
>> ezplot(y2,[0,5]) % Complete Figure 2.3
0.8
y2
0.6
0.4
0.2
y1
y
–0.2
–0.4
–0.6
FIGURE 2.3
Multiple plots.
Executing the preceding script generates a figure which does not exactly match Figure 2.3.
To enable the interactive plot editing mode in the MATLAB figure window, click the Edit
Plot button (Û) or select Tools > Edit Plot from the main menu. If you enable plot editing
mode in the MATLAB figure window, you can perform point-and-click editing of your
graph. In this mode, you can modify the appearance of a graphics object by double-clicking
the object and changing the values of its properties.
A new window (Editor Window) will be opened where the function can be created. The
generic structure of a function is
function A = Circ(r)
%
% Circ calculates the area of a circle of a given radius.
%
% A = Circ(r), where
%
% r is the radius of the circle,
%
% A is the area.
%
A = pi*r^2;
A =
5.3093
Often, functions with multiple outputs are desired. For example, suppose our function
Circ is to return two outputs: area of the circle and the perimeter of the circle. We create
this as follows.
A =
P =
8.1681
2.7.1 Setting Default Values for Input Variables
Sometimes, default values are declared for one or more of the input variables of a func-
tion. As an example, consider a function y_int that returns the y-intercept of a straight
line that passes through a specified point with a given slope. Suppose the slope is 1 unless
specified otherwise; that is, the default value for slope is 1. If the specified point has coordi-
nates (x0, y0) and the slope is m, then the y-intercept is found as y = y0 − mx0. Based on this
we write the function as follows.
function y = y_int(x0,y0,m)
%
% y_int finds the y-intercept of a line passing through a point (x0,y0)
% with slope m.
%
% y = y_int(x0,y0,m), where
%
% x0, y0 are the coordinates of the given point,
% m is the slope of the line (default 1),
%
% y is the y-intercept of the line.
%
if nargin < 3 || isempty(m), m = 1; end
y = y0 - m*x0;
The MATLAB command nargin (number of function input arguments) is used for the
purpose of setting default values for one or more of the input variables. The if statement
here ensures that if the number of input arguments is less than 3, or that the third input
argument is empty, then the default value of 1 will be used for m. As an example, to find
the y-intercept of the line going through the point (−1, 2) with slope 1, either one of the fol-
lowing two statements may be executed:
>> y = y_int(−1,2) % Number of input arguments is less than 3
y =
3
OR
>> y = y_int(−1,2,[]) % The third argument is empty
y =
3
In many cases, at least one of the input variables of a user-defined function happens to
be either a MATLAB function or an anonymous function. Consider the following exam-
ple. Suppose we want to create a user-defined function with the function call [r, k]
= My_func(f,x0,tol,kmax) where f is an anonymous function, x0 is a given initial
value, tol is the tolerance (with default value 1e-4), and kmax is the maximum number
of steps (with default value 20) to be performed. The function calculates x1 = f(x0),
followed by x2 = f(x1), x3 = f(x2), and so on. Operations stop as soon as the
distance between two successive elements generated in this manner is less than tol. The
outputs of the function are the last element generated when the tolerance condition is met,
as well as the number of steps required to achieve that.
function [r, k] = My_func(f,x0,tol,kmax)
if nargin < 3 || isempty(tol), tol = 1e-4; end
if nargin < 4 || isempty(kmax), kmax = 20; end
x = zeros(kmax); % Pre-allocate
x(1) = x0; % Define the first element in the array
for k = 1:kmax,
x(k+1) = f(x(k));
if abs(x(k+1)-x(k)) < tol, % Check tolerance condition
break
end
r = x(k+1); % Set the output as the very last element generated
end
Let us now use My_func for f(x) = 3−x with x0=0, tol=1e-3, and kmax=20.
>> f = @(x)(3^(-x));
>> [r, k] = My_func(f,0,1e-3) % kmax uses default value of 20
r =
0.5473
k =
15
It turns out that the number of steps is 15, which is lower than the maximum of 20. If the
returned value for k happens to be 20, further inspection must be conducted. It is possible
that exactly 20 steps were needed to meet the desired condition. It is also possible that the
maximum number of steps has been exhausted without having the tolerance met. That
is why the function needs to be reexecuted with a larger value of kmax than the default
(in this case, 20) to gather more precise information.
The user-defined function My_func has two outputs: r and k. We may retrieve the
value of r only by executing
>> r = My_func(f,x0,tol,kmax)
This is possible because r is the first output. To have access to the value of k, however,
we must execute
opens the Editor Window, where the script can be created and saved under the name
My_script. It is recommended that a script start with the functions clear and clc.
The first one clears all the previously generated variables, and the second one clears the
Command Window. Suppose we type the following lines in the Editor Window:
clear
clc
x = 2; N = 10;
a = cos(x)*N^2;
While in the Editor Window, select “Run My_script.m” under the Debug pull-down
menu. This will execute the lines in the script file and return the Command Prompt.
Simply type a at the prompt to see the result.
>> My_script
>> a
a =
−41.6147
This can also be done by highlighting the contents and selecting “Evaluate Selection.” An
obvious advantage of creating a script file is that it allows us to simply make changes to the
contents without having to retype all the commands.
2 y + x
a. The subs command.
b. An anonymous function.
1 − 2x x + y
4. Evaluate the matrix function f ( x , y ) = for x = 1, y = −1
0 cos y
a. Using the subs command.
b. By conversion into a MATLAB function.
5. Consider g(t) = t sin ( 12 t ) + ln(t − 1) . Evaluate dg/dt at t = 34
a. Using the subs command.
b. By conversion into a MATLAB function.
6. Consider h( x) = 3 x − 2 sin x + 32 e1− 2 x . Evaluate dh/dx at x = −0.3
a. Using the subs command.
b. By conversion into a MATLAB function.
1/3
7. Evaluate x 2 + e − a( x +1) when a = −1, x = 3 using an anonymous function in
another anonymous function.
8. Evaluate x + ln 1 − e( a+ 2) x/3 when a = −3, x = 1 using an anonymous function in
another anonymous function.
In Problems 9 through 12 write a script file that employs any combination of the flow
control commands to generate the given matrix.
1 0 −1 0 0 0
0 2 0 −1 0 0
2 0 3 0 −1 0
9. A =
0 2 0 4 0 −1
0 0 2 0 5 0
0 0 0 2 0 6
4 1 −2 3 0 0
0 4 −1 2 3 0
0 0 4 1 −2 3
10. A =
0 0 0 4 −1 2
0 0 0 0 4 1
0 0 0 0 0 4
1 1 0 0 0 0
0 −2 2 0 0 0
−1 0 3 3 0 0
11. B =
0 1 0 −4 4 0
0 0 −1 0 5 5
0 0 0 1 0 −6
0 0 −1 0 0
0 −1 0 −2 0
12. B = 4 0 2 0 −3
0 5 0 −3 0
0 0 6 0 4
13. Using any combination of commands diag, triu, and tril, construct matrix B
from A.
2 1 −1 2 0 0 0 0
3 0 4
1 3 0 0 0
A= , B=
1 5 −1 3 1 5 0 0
0 2 6 1 0 2 6 0
14. Using any combination of commands diag, triu, and tril, construct matrix B
from A.
2 1 −1 2 0 1 −1 2
3 0 4
1 3 0 4 1
A= , B=
1 5 −1 3 0 5 0 3
0 2 6 1 0 0 6 0
∫
15. Plot e t − 2 x sin xdx versus −1 ≤ t ≤ 1, add grid and label.
1
t
∫
16. Plot ( x + t)2 e −(t − x )dx versus −2 ≤ t ≤ 1, add grid and label.
0
( )
17. Plot y1 = 31 e − t sin t 2 and y 2 = e − t/2 versus 0 ≤ t ≤ 5 in the same graph. Add grid,
and label.
18. Generate 100 points for each of the two functions in Problem 17 and plot versus
0 ≤ t ≤ 5 in the same graph. Add grid, and label.
∞
sin ω
19. Evaluate
∫
0
ω
dω.
20. Plot u(x, t) = cos(1.7x) sin(3.2t) versus 0 ≤ x ≤ 5 for four values of t = 1, 1.5, 2, 2.5 in a
2 × 2 tile. Add grid and title.
21. Plot u(x, t) = (1 − sin x)e−(t+1) versus 0 ≤ x ≤ 5 for two values of t = 1, 3 in a 1 × 2 tile.
Add grid and title.
22. Given that f(x) = e−2x + cos(x + 1), plot f ′( x) versus 0 ≤ x ≤ 8.
23. Write a user-defined function with function call val = f_eval(f,a,b) where
f is an anonymous function, and a and b are constants such that a < b. The func-
tion calculates the midpoint m of the interval [a, b] and returns the value of
f ( a) + 12 f (m) + f (b) . Execute f_eval for f = e−x/3, a = −4, b = 2.
24. Write a user-defined function with function call m = mid_seq(a,b,tol) where
a and b are constants such that a < b, and tol is a specified tolerance. The function
first calculates the midpoint m1 of the interval [a, b], then the midpoint m2 of [a, m1],
then the midpoint m3 of [a, m2], and so on. The process terminates when two suc-
cessive midpoints are within tol of each other. Allow a maximum of 20 iterations.
The output of the function is the sequence m1, m2, m3, …. Execute the function for
a = −4, b = 10, tol = 10−3.
25. Write a user-defined function with function call C = temp_conv(F) where F
is temperature in Fahrenheit, and C is the corresponding temperature in Celsius.
Execute the function for F = 87.
26. Write a user-defined function with function call P = partial_eval(f,a) where
f is a function defined symbolically, and a is a constant. The function returns the
value of f ′ + f ′′ at x = a. Execute the function for f = 3x2 − ex/3, and a = 1.
27. Write a user-defined function with function call P = partial_eval2(f,g,a)
where f and g are functions defined symbolically, and a is a constant. The function
returns the value of f ′ + g ′ at x = a. Execute the function for f = x2 + e−x, g = sin(0.3x),
and a = 0.8.
28. Write a user-defined function with function call [r, k] = root_finder(f,
x0,kmax,tol) where f is an anonymous function, x0 is a specified value,
kmax is the maximum number of iterations, and tol is a specified tolerance. The
function sets x1 = x0, calculates |f(x1)|, and if it is less than the tolerance, then x1
approximates the root r. If not, it will increment x1 by 0.01 to obtain x2, repeat the
procedure, and so on. The process terminates as soon as |f(xk)|< tol for some k.
The outputs of the function are the approximate root and the number of iterations
it took to find it. Execute the function for f(x) = x2 − 3.3x + 2.1, x0 = 0.5, kmax = 50
tol = 10−2.
29. Repeat Problem 28 for f(x) = 3 + ln(2x − 1)−ex, x0 = 1, kmax = 25 tol = 10−2.
30. Write a user-defined function with function call [opt, k] = opt_finder(fp,
x0,kmax,tol) where fp is the derivative (as a MATLAB function) of a given
function f, x0 is a specified value, kmax is the maximum number of iterations,
and tol is a specified tolerance. The function sets x1 = x0, calculates |fp(x1)|, and
if it is less than the tolerance, then x1 approximates the critical point opt at which
the derivative is near zero. If not, it will increment x1 by 0.1 to obtain x2, repeat the
procedure, and so on. The process terminates as soon as |fp(xk)| < tol for some
k. The outputs are the approximate optimal point and the number of iterations it
took to find it. Execute the function for f(x) = x + (x − 2)2, x0 = 1, kmax = 50 tol = 10−3.