MATLAB Experiential Learning Manual
MATLAB Experiential Learning Manual
MA221TC
MANUAL FOR
EXPERIENTIAL LEARNING
USING MATLAB
II - SEMESTER
Experiential Learning Department of Mathematics
Contents
Introduction 3
Modules 8
1 Vector Differentiation 8
2 Interpolation 11
4 Number Theory 17
Introduction
In Experiential Learning component of first semester Mathematics course - Multivariable Calculus, an
introduction was given to MATLAB software and modules were provided for basic concepts like arithmetic
operations, math built-in functions, visualizing 2D and 3D plots, operations of differential, integral and
vector calculus, and evaluating multiple integrals.
On successful completion of learning these modules, the process continues with Experiential Learning
component of second semester Mathematics course - Differential Equations & Numerical Methods. A
note on scripts and anonymous functions appear which are useful in repeated usage of a set of MATLAB
commands. Further a more rigorous approach is followed in which the modules cover all the basic concepts
of higher Engineering Mathematics like evaluating handling statistical data, solving system of equation,
solving higher order differential equations and implementing numerical techniques on MATLAB.
It is ensured that after going through the MATLAB course as Experiential Learning of Engineering Math-
ematics I and II, a student is well equipped to code any engineering problem successfully.
Scripts are the simplest type of program file. They are useful for automating a series of MATLAB com-
mands, such as computations that are performed repeatedly from the command line or series of commands
referenced.
After saving the script, the code can be run in the following ways:
1. Type the script name on the command line and press Enter. For example, to run a script titled
myMATLABProgram.m script, type myMATLABProgram.
2. Click the Run button on the Editor tab.
Example for a MATLAB Script
The following script calculates the area of a triangle with base ‘b’ and height ‘h’.
b = 5;
h = 3;
a = 0.5*(b*h)
This can be saved as triarea.m, run the script, by typing triarea on the MATLAB Command
Prompt or click the Run button on the Editor tab.
Writing the comment lines in MATLAB script will help the user to understand the code.
Add comments to MATLAB code using the percentage (%) symbol. Comment lines can appear anywhere
in a program file and comments can be appended at the end of a line of code.
%This script calculates the area of a triangle with base ‘b’ and height ‘h’
b = 5; % Base
h = 3; % Height
a = 0.5*(b*h) % Area
web(fullfile(docroot, ’matlab/scripts.html’))
Live Scripts
To combine code with embedded output, formatted text, equations and images in a single interactive envi-
ronment, create live scripts.
Live scripts are program files useful for interacting with a series of MATLAB commands and their output.
Live scripts contain output and graphics with the code that produced them, together in a single interactive
environment called the Live Editor. Add formatted text, images, hyperlinks and equations to live scripts
to produce an interactive narrative that can be shared with others. Live scripts are stored as files .mlx
extension.
To create a new live script, on the Home tab, in the New drop-down menu, select Live Script.
To obtain more information on Live Scripts, type the following in the Command Window:
Valid script names follow the same rules as variable names. It must start with a letter and can be followed
by letters, digits, or underscores.
MATLAB Functions
Both scripts and functions allow to reuse sequences of commands by storing them in program files. Scripts
are the simplest type of program, since they store commands exactly as it is typed at the command line.
Functions provide more flexibility, as primarily user can pass input values and return output values. For
example, the following function named fact computes the factorial of a number (n) and returns the result
(f).
function f = fact(n)
f = prod(1:n);
end
This type of function must be defined within a file, not at the command line. The best practice is to use the
same name for the function and the file (in this example, fact.m), since MATLAB associates the program
with the file name.
The function can be called from the command line, using the same syntax rules that apply to functions
installed with MATLAB. For instances, calculate the factorial of 5.
x = 5;
y = fact(x);
To create a MATLAB function, open the MATLAB Editor by typing edit in the Command Window.
The first line of every function is the definition statement, which includes the following elements.
Valid function names follow the same rules as variable names. It must start with a letter and can be followed
by letters, digits, or underscores.
The body of a function can include valid MATLAB expressions, control flow statements, comments, blank
lines and nested functions. Note that any variables can be created within a function and are stored within a
workspace specific to that function, which is separate from the base MATLAB workspace.
End Statements
Typically, functions end with an end statement at the end of the file. Although it is optional, use end for
better code readability.
Scripts vs Functions
For a comparison on scripts and functions and when to use them, go over the documentation in:
Anonymous Functions
What Are Anonymous Functions?
An anonymous function is a function that is not stored in a program file. It is associated with a variable
whose data type is function handle. Anonymous functions can accept inputs and return outputs, just
as standard functions do. However, they can contain only a single executable statement.
For example, create a function handle to an anonymous function that finds the square of a number:
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, similar to passing an
input argument to a standard function.
a = sqr(5)
Many MATLAB functions accept function handles as inputs so that functions can be evaluated over a range
of values. Handles can be created either for anonymous functions or for functions in program files. The
benefit of using anonymous functions is that not to edit and maintain a file for a function that requires only
a brief definition.
where µ > 0 is a scalar parameter. Rewrite this equation as a system of first-order ODEs by making the
substitution y10 = y2 . The resulting system of first-order ODEs is
y10 = y2
y20 = µ(1 − y12 )y2 − y1 .
The function vdpeval represents the van der Pol equation using µ = 1. The variables y1 and y2 are the
entries y(1) and y(2) of a two-element vector, dydt.
Solve the ODE using the ode45 function on the time interval [0 20] with initial values [2 0]. The
resulting output is a column vector of time points t and a solution array y. Each row in y corresponds
to a time returned in the corresponding row of t. The first column of y corresponds to y1 and the second
column to y2 .
plot(t,y(:,1),’--’,t,y(:,2),’-.’)
title(’Solution of van der Pol Equation (\mu = 1) with ODE45’);
xlabel(’Time t’);
ylabel(’Solution y’);
legend(’y_1’,’y_2’)
1
Solution y
-1
-2
-3
0 5 10 15 20
Time t
Modules
1 Vector Differentiation
Topic learning outcomes:
Student will be able to:
1. Understand the existence of vector functions, derivatives of vector functions and rules of differenti-
ation and fundamentals of the integration of vector point function.
2. The importance of defining vector differential operator and the operations- Gradient of scalar point
functions, Divergence and Curl of vector point functions.
Example 1.1. Find the gradient vector of 2yzsin(x) + 3xsin(z)cos(y) with respect to vector [x,y,z].
syms x y z
f(x,y,z) = 2*y*z*sin(x) + 3*x*sin(z)*cos(y);
gradient(f,[x,y,z])
3 cos (y) sin (z) + 2 y z cos (x)
ans(x, y, z) = 2 z sin (x) − 3 x sin (y) sin (z)
2 y sin (x) + 3 x cos (y) cos (z)
Example 1.2. Find the gradient of a function −(sin(x) + sin(y))2 with respect to vector [x,y]., and
plot it as a quiver (velocity) plot
syms x y
f = -(sin(x) + sin(y))ˆ2;
g = gradient(f,[x,y])
−2 cos (x) (sin (x) + sin (y))
g=
−2 cos (y) (sin (x) + sin (y))
Now plotting the vector field defined by these components. MATLAB provides the quiver plotting
function for this task. The function does not accept symbolic arguments. First, replace symbolic variables
in expressions for components of g with numeric values. Then use quiver.
[X, Y] = meshgrid(-1:.1:1,-1:.1:1);
G1 = subs(g(1),[x y],{X,Y});
G2 = subs(g(2),[x y],{X,Y});
quiver(X,Y,G1,G2)
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
Example 1.3. Find the divergence of the vector field V (x, y, z) = (x, 2y 2 , 3z 3 ) with respect to vector
X = (x, y, z).
syms x y z
f = [x 2*yˆ2 3*zˆ3];
v = [x y z];
divergence(f,v)
ans = 9z 2 + 4y + 1
syms x y z
f = xˆ2 + yˆ2 + zˆ2;
divergence(gradient(f,vars),vars)
ans = 6
Example 1.5. Compute the curl of the vector field V (x, y, z) = (x3 y 2 z, y 3 z 2 x, z 3 x2 y) with respect to
vector X = (x, y, z) in Cartesian coordinates.
syms x y z
V = [xˆ3*yˆ2*z, yˆ3*zˆ2*x, zˆ3*xˆ2*y];
X = [x y z];
curl(V,X)
Example 1.6. Compute the curl of the gradient of the scalar function x2 + y 2 + z 2 .
syms x y z
f = xˆ2 + yˆ2 + zˆ2;
vars = [x y z];
curl(gradient(f,vars),vars)
ans = (0, 0, 0)
Exercise:
1. Gradient of scalar measure the increase or decrease of a quantity along some direction, Find the
gradient vector of xy 2 z 3 − x3 y 2 z with respect to vector [x,y,z].
2. The steepness of the slope at that point is given by 2x3 y 2 z 4 . Find the divergence of the gradient of
scalar function.
3. A person on a hang glider is spiraling upward due to rapidly rising air on a path having a vector
x y
field F (x, y, z) = ( , ). Find the divergence of the vector field with respect to vector
x+y x+y
X = (x, y).
4. Show that the uniform motion of a projectile along a meridian of the rotating earth is given by the
vector function V (x, y, z) = (2xyz, xy − y 2 z, x2 − zx) is solenoidal.
5. The velocity vector field for the three-dimensional flow of an ideal fluid around a cylinder is given
by F (x, y, z) = (sinx + z, cosy − z, x − y). Show that F (x, y, z) is irrotational.
6. The temperature of all points in a room at a particular time is a scalar field, then compute the curl of
the gradient of the scalar function x2 y + 2xy + z 2 .
2 Interpolation
Topic learning outcomes:
Student will be able to:
1. Interpolate from equally and unequally spaced domain points.
2. Extrapolate for evaluating points that lie outside the domain.
3. Use this concept to solve real life and engineering problems.
Method Description
‘linear’ Linear interpolation.
‘nearest’ Nearest neighbor interpolation.
‘next’ Next neighbor interpolation.
‘previous’ Previous neighbor interpolation.
‘pchip’ Shape-preserving piecewise cubic interpolation.
‘cubic’ Same as ‘pchip’.
‘spline’ Spline interpolation using not-a-knot end conditions.
Example 2.1. Using interpolation process find the value of sin 48o .
x = 0:5:90;
v = sind(x);
xq = 48;
vq1 = interp1(x,v,xq)
vq1 =
0.7425
Example 2.2. The following table gives the distances (in miles) of the visible horizon for the given heights
(in feet) above the earth’s surface.
x = 200:50:400;
v = [15.04 16.81 18.42 19.9 21.27];
xq = [218 389];
vq1 = interp1(x,v,xq)
vq3 = interp1(x,v,xq,’spline’)
vq1 =
15.6772 20.9686
vq3 =
15.6977 20.9771
Example 2.3. The area A of a circle for different diameters d is given in the following table:
d: 80 85 90 95 100
A: 5026 5674 6362 7088 7854
x=[80 85 90 95 100];
y= [5026 5674 6362 7088 7854];
xq=105;
yq1=interp1(x,y,xq,’pchip’)
vq3 = interp1(x,y,xq,’spline’)
yq1 =
8.6589e+03
vq3 =
8663
Example 2.4. The following table gives the viscosity of oil as a function of temperature. Find the viscosity
of oil at a temperature of 140o .
yq1 =
7.0333
Exercise:
1. Estimate the population in 1895 and 1925 from the following statistics:
3. The pressure p of wind corresponding to velocity v is given in following table. Estimate p when v = 25,
35, 45.
Year v : 10 20 30 40
Population p : 1.1 2 4.4 7.9
4. A rod is rotating in a plane. The following table gives the angle θ (radians) through which the rod has
turned for various values of the time t second.
1. Solve linear differential equations of second and higher order with constant coefficients.
2. Solve linear differential equations of second and higher order with variable coefficients.
d y 2 dy
Example 3.1. Solve 2x2 dx2 + 3x dx − y = 0.
syms y(x)
dsolve(2*xˆ2*diff(y, 2) + 3*x*diff(y) - y == 0)
ans =
C1/(3*x) + C2*xˆ(1/2)
Example 3.2. Solve the boundary value problem y 00 + 6y 0 + 9y = 2e−3x , y(0) = 0 and y(1) = 1.
syms y(x)
dsolve(diff(y, 2)+6*diff(y) +9*y == 2*exp(-3*x),y(0)==0,y(1)==1)
ans =
xˆ2*exp(-3*x) + x*exp(-3*x)*(exp(3) - 1)
Example 3.3. Obtain the solution of the differential equation (D4 − 1)y = cos 2x cosh x.
syms y(x)
simplify(dsolve(diff(y, 4)-y == cos(2*x)*cosh(x)))
ans =
Example 3.4. A 32 lb weight is suspended from a spring having constant 4 lb/ft. Find position of weight
at any time, if a force 16 sin 2t is applied and damping force is negligible. Assume that initially the weight
is at rest in the equilibrium position.
d2 x
dt2
+ 4x = 16 sin 2t; x(0) = 0, x0 (0) = 0.
syms x(t)
Dx=diff(x);
simplify(dsolve(diff(x, 2)+4*x == 16*sin(2*t),x(0)==0,Dx(0)==0))
ans =
2*sin(2*t) - 4*t*cos(2*t)
Example 3.5. A horizontal beam of length 2lf t is freely supported at both ends. Find the maximum
deflection if the load is w per unit length.
Hint:
Let P be any point (x, y) on the elastic curve. The total weight supported is 2lw. Hence the upward thrust
of the support at each end is lw. Consider the segment OP of the beam. The forces acting in this region are
upward thrust lw at zero and load wx acting at the midpoint of OP then the differential equation describing
this phenomena is
2
d y wx2
El dx 2 = 2 − wlx, under the boundary conditions y(0) = 0, y(2l) = 0.
syms y(x) E l w
dsolve(E*l*diff(y, 2) == (w*xˆ2/2)-w*l*x, y(0) == 0,y(2*l) == 0)
max_deflection=subs(ans,x,l)
ans =
(5*lˆ3*w)/(24*E)
Exercise:
1. Find the transient and steady state solutions of the mechanical system corresponding to the differen-
2
tial equation ddt2x + 2 dx dx
dt + 2x = sin 2t − 2 cos 2t; x(0) = 0, dt (0) = 0.
2. In the case of a stretched elastic spring which has one end fixed and a particle of mass m attached
2
at the other end, the equation of motion is m ddt2x = − mg
e (x − l) where l is the natural length of the
string and e is the elongation due to weight mg. Find x under the condition that at t = 0, x = a and
dx
dt = 0.
3. The deflection of a strut of length l with one end (x = 0) built-in and the other supported subjected
d2 y 2 a2 R dy
to end thrust p satisfies the equation dx 2 + a y = p (l − x), y = 0, dx = 0 at x = 0. Find the
deflection.
4. An electric circuit consists of an inductance of 0.05 Henrys, a resistance of 5 Ohms and a condenser
of capacitance 4 × 10−4 Farad and a constant emf of 110 Volts. Governing differential equation is
d2 Q
dt2
+ 100 dQ
dt + 50000Q = 2200, under the conditions Q(0) = I(0) = 0. Determine charge Q(t).
4 Number Theory
Topic learning outcomes:
Student will be able use built-in functions to:
>> divisors(42)
ans =
1 2 3 6 7 14 21 42
Example 4.2. Calculate the greatest common divisor of the integers 4420, −128, 8984, −488.
A =
[4420, -128, 8984, -488]
ans =
4
Example 4.3. Obtain the next prime number greater than 123.
>> nextprime(123)
ans =
127
>> nthprime(153)
ans =
883
Example 4.5. Determine the 10th, 100th, and 1000th prime numbers.
ans =
29 541 7919
Example 4.6. Find the largest prime number smaller than 82.
>> prevprime(82)
ans =
79
T =
0 0 1 1
ans =
>> mod(87, 5)
ans =
>> factor(120)
ans =
2 2 2 3 5
>> eulerPhi(120)
ans =
40
Example 4.12. Calculate Euler function φ(n) for the integers 12, 29, 120.
ans =
4 28 32
Example 4.13. Determine the remainder and quotient of the polynomials x3 y 4 − 2xy + 5x + 1, and xy
syms x y
p1 = xˆ3*yˆ4 - 2*x*y + 5*x + 1;
p2 = x*y;
[q, r] = quorem(p1, p2, y)
q =
xˆ2*yˆ3 - 2
r =
5*x + 1
Exercise:
1. Find the greatest common divisor of the integers 20, 50 and 120.
4. Obtain the largest prime number smaller than 32, 149, 2019.
‘fitType’ are :
x = [1 6 11 16 20 26];
y =[13 16 17 23 24 31];
f=fit(x’,y’,‘Poly1’)
plot(f,x,y)
Example 5.2. The following table gives the results of the measurements of train resistances; V is the
velocity in mile per hour and R is the resistance in pound per ton.
x 20 40 60 80 100 120
y 2.2 9.1 14.9 22.8 33.3 46
Example 5.4. Fit a curve of the form y = aebx to the data by the method of least squares.
x 0 2 4
y 8.12 10 31.82
x=[0 2 4];
y=[8.12 10 31.82];
f=fit(x’,y’,‘Exp1’)
plot(f,x,y)
Example 5.5. The following table gives the stopping distance y in meters of a motor bike moving at a
speed of x kms/hour when the breaks are applied.
x 16 24 32 40 48 56
y 0.39 0.75 1.23 1.91 2.77 3.81
Find the correlation coefficient between the speed and the stopping distance, and the equations of regres-
sion lines.
r = 0.9827
m = 0.0851
b = -1.2551
Exercise:
1. Estimate the mean radiation dose at an altitude of 3000 ft by fitting a curve y = aex to the given
data:
2. The latent heat of vaporisation of steam r is given in the following table at different temperature t:
x 40 50 60 70 80 90 100 110
y 1069.1 1063.6 1058.2 1052.7 1049.3 1041.8 1036.3 1030.8
3. The following data represent carbon dioxide(co2 ) emission from coal-fluid boilers (In units of 1000
tons) over a period of years 2005 to 2017. The variable (year) has been standardized and yield
following table.
Years, x 0 5 8 9 10 11 12
co2 emmision, y 910 680 520 450 370 350 340
4. Obtain the lines of regression and hence find the coefficient of correlation for the following data
x 1 3 4 2 5 8 9 10 13 15
y 8 6 10 8 12 16 16 10 32 32
VISION
Disseminate Scientific and Engineering knowledge through quality teaching and
research partnership.
MISSION
Develop a spirit of competence to face challenges of the rapidly changing
teaching methodology.
Motivate faculty and scholars to acquire the latest skills for mathematical
modeling for modern technology application.
Develop positive attitude towards continuous learning.
Undertake inter-disciplinary research partnership.
Impart quality education through effective teaching process.
Provide extension programs for assisting individuals and organizations to find
solutions to engineering problems through consultation and research.
Impart skills on passing out-graduates to become excellent thereby enabling
them to make significant contribution in their chosen profession.
RV COLLEGE OF ENGINEERING ®
R. V. Vidyaniketan Post, Mysuru road
Tel: +91-80-67178021, 67178099 Fax: +91-80-67178011
www.rvce.edu.in