Matlab Manual Engineering Maths II
Matlab Manual Engineering Maths II
RV COLLEGE OF ENGINEERING®
(Autonomous Institution Affiliated to VTU, Belagavi)
DEPARTMENT OF MATHEMATICS
ENGINEERING MATHEMATICS - I
18MA11
MANUAL FOR
EXPERIENTIAL LEARNING
USING MATLAB
I - SEMESTER
MATLAB Manual
Department of Mathematics, RV College of Engineering
Contents
Introduction 3
Modules 6
1 Arithmetic Operations 6
6 Differentiation 29
7 Integration 31
2
Experiential Learning Department of Mathematics
Introduction
MATLAB (MATrix LABoratory)
MATLAB is a software package for high performance numerical computation and visualization. It provides
an interactive environment with hundreds of built-in functions for technical computation, graphics and an-
imation. Best of all it also provides easy extensibility with its own high-level programming language. The
name MATLAB stands for MATrix LABoratory. It has powerful built-in routines that enable a very wide
variety of computations. It possesses easy to use graphics commands that make the visualization of results
immediately available. Specific applications are executed using tool boxes, which are a collection of routines
that are designed to do common things. There are toolboxes for signal processing, symbolic computation,
control theory, simulation, optimization and several other fields of applied science and engineering.
3. Sign in using your MathWorks Account with your RVCE email address.
4. If you do not have a MathWorks Account with your RVCE email address, click on Create Account
5. Complete the steps to create your MathWorks Account (If you have any trouble creating an account,
contact MathWorks Customer Service via [email protected] or + 91-80-6632-6000)
6. Once logged in on the Portal, you would automatically be associated to the RVCE MATLAB Campus-
Wide License.
Installing MATLAB
Detailed installation instructions can be found in the link below:
https://www.mathworks.com/matlabcentral/answers/98886
For any installation issues, contact the MathWorks Install Support team at: [email protected] or call +
91-80-6632-6000
4. In the installer, select Log in with a MathWorks Account and follow the online instructions.
5. When prompted to do so, select the Academic Total Headcount license labeled Individual.
7. After downloading and installing your products, keep the Activate MATLAB checkbox selected and
click Next.
• Disk Space requirement: 2GB for MATLAB only. However, a disk space of 4-6 GB is recom-
mended.
Command History- The commands typed in the command window automatically get recorded and stored
in command history day wise. These can be retrieved any time for execution. The command history gets
cleaned only when the command ‘Clear Command History’ is used.
Modules
1 Arithmetic Operations
Topic learning outcomes:
Student will be able to:
1. Understand how to use MATLAB as a calculator to carry out arithmetic operations such as addition,
subtraction, multiplication, division and exponentiation.
2. Use format commands to control floating point output display.
3. Execute arithmetic expressions involving various operations.
• format short- Fixed-decimal format with 4 digits after the decimal point.
• format long - Fixed-decimal format with 15 digits after the decimal point.
37
Example 1.1: Calculate 54 .7.62 + (93 −652)
.
(5/4)*7*6ˆ2+(3ˆ7/(9ˆ3-652))
ans =
343.4026
(5−2i)
Example 1.2: Evaluate (2 + 3i)(4 − i) + (3−7i) .
(2+3*i)*(4-i)+((5-2*i)/(3-7*i))
ans =
11.5000 +10.5000i
Exercise:
sin - Sine
cos - Cosine
tan - Tangent
sec - Secant
csc - Cosecant
cot - Cotangent
exp - Exponential
ab - Absolute value
Note: MATLAB users need not have to remember the syntax. Each MATLAB function has supporting doc-
umentation that includes description of function inputs, outputs, calling syntax and examples. For this click
the help button on the toolbar which opens Help browser. Enter search terms in Search Documentation
box.
Variables
Variables are generally denoted symbolically by individual characters (like 0 a0 or 0 x0 ). Symbolic Math Tool-
box introduces a special data type - symbolic objects. This data type includes symbolic numbers, symbolic
variables, symbolic expressions and symbolic functions. It also includes vectors, matrices and multidi-
mensional arrays of symbolic numbers, variables, expressions, and functions. Using symbolic objects in
computations indicates that MATLAB must perform these computations analytically instead of numerically.
Symbolic computations are exact and are not prone to round-off errors.
ans =
5
ans =
-1
ans =
6
ans =
1.5000
ans =
0.9093
ans =
7.3891
ans =
-6.5551
ans =
y
ans =
x
x+iy
Example 2.3: Find real and imaginary part of function x+2iy + sin(x + i y2 ).
syms x y real
g=(x+i*y)/(x+2*i*y)+sin(x+i*y/2);
imag(g)
real(g)
ans =
sinh(y/2)*cos(x) - (x*y)/(xˆ2 + 4*yˆ2)
ans =
xˆ2/(xˆ2 + 4*yˆ2) + (2*yˆ2)/(xˆ2 + 4*yˆ2) + cosh(y/2)*sin(x)
ans =
exp(x)*sin(y)
ans =
exp(x)*cos(y)
Arrays
An important aspect in programming is that of an array (or matrix). This is just an ordered sequence of
numbers (known as elements).
Array Operations
Array operations work on corresponding elements of arrays with equal dimensions. Each element in the
first operand gets matched up with the element in the same location in the second operand. The following
table provides a summary of arithmetic array operators in MATLAB.
Example 2.5: Express the following numbers as row and column vectors : 1, 22, -0.4.
[1 22 -0.4]
[1;22;-0.4]
ans =
1.0000 22.0000 -0.4000
ans =
1.0000
22.0000
-0.4000
x=[5 2 1 6 7]
x =
5 2 1 6 7
x=[1:5]
x =
1 2 3 4 5
y=[-3:2:9]
y =
-3 -1 1 3 5 7 9
z=linspace(0,25,5)
z =
0 6.2500 12.5000 18.7500 25.0000
x2 −1
Examples 2.10: Find the value of 2x+3 at the points 1, 5, -7, 1/2.
y =
0 1.8462 -4.3636 -0.1875
Note: Here ‘.’ is used before the operators to perform element-wise operation.
Exercise:
443z e−xz
1. Define the variable x and z as x = 9.6 and z = 8.1, then evaluate 2x3
+ (x+z) .
2. A triangle has sides a = 18cm, b = 35cm and c = 50cm. Define a, b and c as variables and calculate the
angle γ by using the law of cosines: c2 = a2 + b2 − 2ab cos γ.
4. Calculate the radius ‘r’ of a sphere that has a volume of 350 inch3 .
Cartesian curves
Syntax and description:
• plot(X,Y)- creates a 2-D line plot of the data in Y versus the corresponding values in X.
• plot(X,Y,LineSpec)- sets the line style, marker symbol, and color.
• plot(X1,Y1,...,Xn,Yn)- plots multiple X, Y pairs using the same axes for all lines.
• plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn)- sets the line style, marker type, and
color for each line. You can mix X, Y, LineSpec triplets with X, Y pairs. For example,
plot(X1,Y1,X2,Y2,LineSpec2,X3,Y3).
• ezplot(f,[min,max])- plots f over the specified range. If f is a univariate expression or
function, then [min,max] specifies the range for that variable. This is the range along the abscissa
(horizontal axis). If f is an equation or function of two variables, then [min,max] specifies the
range for both variables, that is the ranges along both the abscissa and the ordinate.
• ezplot(f,[xmin,xmax,ymin,ymax])- plots f over the specified ranges along the abscissa
and the ordinate.
Line Style:
‘ - ’ (default solid line) | ‘ – ’ (dashed line) | ‘ : ’ (dotted line) | ‘ -.’ (dashed-dotted line) | ‘ none ’ (no line)
Marker Symbol:
Symbol Description
o Circle
+ Plus sign
∗ Asterisk
. Point
x Cross
square or s Square
diamond or d Diamond
ˆ Upward-pointing triangle
v Downward-pointing triangle
> Right-pointing triangle
< Left-pointing triangle
pentagramorp Five-pointed star (pentagram)
hexagramorh Six-pointed star (hexagram)
none No markers
Commands for labeling along the x-axis and y-axis, adding title and grid lines
Example 3.1: Define x as a vector of linearly spaced values between 0 and 2π. Use an increment of π/100
between the values. Plot y as sine values of x.
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
Example 3.2: Define x as 100 linearly spaced values between −2π and 2π. Assign y1 and y2 as sine and
cosine values of x. Create a lineplot of both sets of data.
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
plot(x,y1,x,y2)
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
-8 -6 -4 -2 0 2 4 6 8
Example 3.3: Plot three sine curves with a small phase shift between each line. Use the default line style
for the first line. Specify a dashed line style for the second line and a dotted line style for the third line.
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
plot(x,y1,x,y2,’--’,x,y3,’:’)
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
Example 3.4: Create a 2-D line plot of the cosine curve. Change the line color to a shade of blue-green
using an RGB color value. Add a title and axis labels to the graph using the title, xlabel and ylabel
commands.
x = linspace(0,10,150);
y = cos(5*x);plot(x,y,’Color’,[0,0.7,0.9])
title(’2-D Line Plot’)
xlabel(’x’)
ylabel(’cos(5x)’)
0.8
0.6
0.4
0.2
cos(5x)
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7 8 9 10
x
syms x y
ezplot(yˆ2*(2-x)-xˆ2*(2+x),[-2,2]) % To plot implicit functions
title(’Strophoid’)
xlabel(’x’)
ylabel(’y’)
grid on
Strophoid
2
1.5
0.5
0
y
-0.5
-1
-1.5
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
x
Polar curves
Syntax and description:
• polarplot(theta,rho)- plots a line in polar coordinates, with theta indicating the angle in
radians and rho indicating the radius value for each point. The inputs must be vectors with equal
length or matrices with equal size. If the inputs are matrices, then polarplot plots columns of rho
versus columns of theta. Alternatively, one of the inputs can be a vector and the other a matrix as
long as the vector is the same length as one dimension of the matrix.
• polarplot(theta,rho,LineSpec)- sets the line style, marker symbol and color for the line.
syms r theta
theta = 0:0.01:2*pi;
r = 2*sin(3*theta);
polarplot(theta,r)
90
2
120 60
1.5
150 30
1
0.5
180 0 0
210 330
240 300
270
Example 3.7: Plot the graph of Cardiod given by r = 3(1 + cos θ).
theta = 0:0.01:2*pi;
r = 3*(1+cos(theta));
polarplot(theta,r)
90
6
120 60
4
150 30
180 0 0
210 330
240 300
270
Exercise:
3. An array speaker emits audio waves with peak amplitude of 3db and transmits in two directions. Plot the
curve using MATLAB.
Hint: Equation of the curve in polar form is: r = 3 cos(2θ).
Definitions:
Mean: It is the average and is computed as the sum of all the observed outcomes from the sample divided
by the total number of events.
Median: If the values of a variable are arranged in the ascending order of magnitude, the median is the
middle term if the number is odd and is the mean of two middle terms if the number is even.
Mode: It is that value of the variable which occurs most frequently, i.e., the value of the maximum fre-
quency.
Standard deviation: It is the positive square root of the mean of the squares of the deviation from the
arithmetic mean.
Variance: It is the square of standard deviation.
var - Variance
Example 4.1: The crushing strength of 10 cement concrete experimental blocks, in metric tonnes per square
cm was 4.4, 5.0, 3.8, 9.6, 4.2, 4.7, 4.0, 3.9, 4.6 and 5.0. Find mean, median, mode, standard deviation and
variance of the crushing strength of the blocks.
A=[4.4, 5.0, 3.8, 9.6, 4.2, 4.7, 4.0, 3.9, 4.6, 5.0]
mean(A)
mode(A)
median(A)
var(A)
std(A)
ans =
4.9200
ans =
5
ans =
4.5000
ans =
2.8884
ans=
1.6995
You can import data from spreadsheet files into MATLAB interactively, using the Import Tool or program-
matically using an import function.
Example 4.2: Find mean, standard deviation of first and second test marks obtained by 58 students of CS
branch.
Hint: Go to Home. Click import data and open the excel file, select the required columns
Import data from excel file and name the matrix as ’A’, select numeric matrix and click import selection.
Then write the syntax for finding mean, standard deviation.
mean(A)
std(A)
ans =
4
ans =
2.1602
Exercise:
1. The tensile strength in megaPascals for 15 samples of tin were determined and found to be: 34.61, 34.57,
34.40, 34.63, 34.63, 34.51, 34.49, 34.61, 34.52, 34.55, 34.58, 34.53, 34.44, 34.48 and 34.40. Calculate the
mean and standard deviation for these 15 values, correct to 4 significant figures.
2. The values of capacitances in microfarads of ten capacitors selected at random from a large batch of
similar capacitors are: 34.3, 25.0, 30.4, 34.6, 29.6, 28.7, 33.4, 32.7, 29.0 and 31.3. Determine the standard
deviation of capacitances for these capacitors, correct to 3 significant figures.
3. The runs scored by 11 members of a cricket team are 25, 39, 53, 18, 65, 72, 0, 46, 31, 08, 34. Find mean,
median, mode and standard deviation of score.
4. The age (in years) of ten teachers in a school are 34, 37, 53, 46, 52, 43, 31, 36, 40, 50. Calculate mean,
median, mode and variance of age.
Bar graph
Syntax and description:
• bar(y) - creates a bar graph with one bar for each element in y. If y is a matrix, then bar groups
the bars according to the rows in y.
• bar(x,y) - draws the bars at the locations specified by x.
• bar( ,width)- sets the relative bar width, which controls the separation of bars within a group.
Specify width as a scalar value. Use this option with any of the input argument combinations in the
previous syntaxes.
• bar( ,style)- specifies the style of the bar groups. For example, use ‘stacked’ to display each
group as one multicolored bar.
• bar( ,color) - sets the color for all the bars. For example, use ’r’ for red bars.
Example 5.1: Create bar graph for vector y = [75 91 105 123.5 131 150 179 203 229 250 281.5].
y = [75 91 105 123.5 131 150 179 203 229 250 281.5];
bar(y)
300
250
200
150
100
50
0
1 2 3 4 5 6 7 8 9 10 11
Example 5.2: The following data shows one country population (in millions) from 1900 to 2000.
Year of census 1900 1910 1920 1930 1940 1950 1960 1970 1980 1990 2000
Population 75 91 105 123.5 131 150 179 203 226 249 281.5
Specify the bar locations along the x-axis and set the width of each bar to 40 percent of the total space
available for each bar. Give red color to all bars.
x = 1900:10:2000;
y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(x,y,0.4,’r’) %‘r’ for red color
300
250
200
150
100
50
0
1900 1910 1920 1930 1940 1950 1960 1970 1980 1990 2000
Example 5.3: The following table shows, three persons visit number of places in four days.
y = [2 1 3; 2 5 7; 2 8 9; 2 11 12];
bar(y)
12
10
0
1 2 3 4
Example 5.4: In example 3, display one bar for each day. The height of each bar is the sum of the places
visited in one day.
z = [2 1 3; 2 5 6; 2 8 9; 2 11 12];
bar(z,’stacked’)
25
20
15
10
0
1 2 3 4
Example 5.5: Production of two items in three months are given below:
Month 1 Month 2 Month 3
Production of Item 1(no.) 1 2 3
Production of Item 2(no.) 4 5 6
Create a figure with two subplots. In the upper subplot, plot a bar graph. In the lower subplot, plot a stacked
bar graph of the same data.
y = [1 2 3; 4 5 6];
ax1 = subplot(2,1,1);
bar(ax1,y)
ax2 = subplot(2,1,2);
bar(ax2,y,’stacked’)
6
0
1 2
15
10
0
1 2
Pie Chart
Syntax and description:
• pie(X) draws a pie chart using the data in X. Each slice of the pie chart represents an element in X.
i) If sum(X)≤ 1, then the values in X directly specify the areas of the pie slices. pie draws only a partial
pie if sum(X) < 1
ii) If sum(X) > 1, then pie normalizes the values by X/sum(X) to determine the area of each slice of the pie.
iii) If X is of data type categorical, the slices correspond to categories. The area of each slice is the number
of elements in the category divided by the number of elements in X.
• pie(X,labels) specifies text labels for the slices. The number of labels must equal the number
of slices. X must be numeric.
• pie(ax, ) plots into the axes specified by ax instead of into the current axes (gca). The option
ax can precede any of the input argument combinations in the previous syntaxes.
Example 5.6: Create pie charts for vectors X = [1 3 0.5 2.5 2], Y = [0.1 0.3 0.2 0.25 0.15] and Z = [0.2 0.15
0.05 0.3].
Example 5.7: The marks obtained by a student in his annual examination are given below:
Subject Maths Electronics Civil Computer Physics
Marks obtained 90 75 72 58 63
Draw a pie chart to represent the above data.
X=[90 75 72 58 63];
labels = {’Maths’,’Electronics’,’Civil’,’Computer’,’Physics’};
pie(X,labels)
Y = [24 46 30];
ax2 = subplot(1,2,2);
pie(ax2,Y,labels)
title(ax2,’2015’)
2014 2015
Taxes
Taxes
Profit
Profit
Expenses
Expenses
Exercise:
1. The number of cars produced in a factory during five consecutive weeks is given below:
2. The following table shows the export earnings of India (in crores) during five consecutive years:
3. The number of electric bulbs sold in a shop during a week is given in the following table:
Day Mon Tue Wed Thu Fri Sat
No. of bulbs sold 225 100 200 150 75 120
Create a pie chart to represent the above data.
6 Differentiation
Topic learning outcomes:
Students will be able to:
1. Differentiate symbolic expression or functions of one or several variables with respect to one or more
independent variables upto required order.
2. Use this to solve application problems such as obtaining velocity and acceleration from displacement
function.
•
diff(F) differentiates F with respect to the variable determined by symvar(F,1).
•
diff(F,var) differentiates F with respect to the variable var.
diff(F,n) computes the nth derivative of F with respect to the variable determined by symvar.
•
diff(F,var,n) computes the nth derivative of F with respect to the variable var.
•
•
diff(F,var1,...varN) differentiates F with respect to the variables var1,...,varN.
√ 2
(x +1)
Example 6.1: Find the first derivative of x .
syms x y
y1=diff((xˆ2+1)ˆ(1/2)/x,x)
y1 =
1/(xˆ2 + 1)ˆ(1/2) - (xˆ2 + 1)ˆ(1/2)/xˆ2
1
Example 6.2: Find second order derivative of (sinx+cosx) .
syms x
diff(1/(sin(x)+cos(x)),x,2)
ans =
1/(cos(x) + sin(x)) + (2*(cos(x) - sin(x))ˆ2)/(cos(x) + sin(x))ˆ3
∂f ∂f ∂ 2 f ∂2f
Example 6.3: If f (x) = yex + x2 y − log(xy), find ∂x , ∂y , ∂x∂y and ∂x2
.
syms x y
f=y*exp(x)+xˆ2*y-log(x*y);
diff(f,x)
diff(f,y)
diff(f,x,y)
diff(f,x,x)
ans =
2*x*y + y*exp(x) - 1/x
ans =
exp(x) + xˆ2 - 1/y
ans =
2*x + exp(x)
ans =
2*y + y*exp(x) + 1/xˆ2
∂f
Example 6.4: Find ∂x at x = 2 , y = 3 if f (x) = x2 y.
syms x y
f=xˆ2*y;
z=diff(f,x);
subs(z,{x,y},{2,3})
ans =
12
Example 6.5: If the motion of a particle is s = aet + be−t . Show that the acceleration is always equal to
displacement s.
syms t a b
diff(a*exp(t)+b*exp(-t),t,2)
ans =
a*exp(t) + b*exp(-t)
Exercise:
1. If s is the distance traversed in meters by a particle in time t sec and s = 4t3 − 6t2 + t − 7, find the
velocity and acceleration when t = 2 sec.
dy d2 y
2. If y = cos4 (log x) + eax sin(bx), find dx and dx2
.
∂2f ∂2f
3. Show that the function f = cosx coshy satisfies 2-dimensional Laplace’s equation: ∂x2
+ ∂y 2
= 0.
∂2u 1 ∂u 1 ∂2u
4. If u = eaθ cos(a log r), show that ∂r2
+ r ∂r + r2 ∂θ2
= 0.
7 Integration
Topic learning outcomes:
Student will be able to:
1. Evaluate definite and indefinite integrals.
2. Use this to solve application problems such as finding area.
• int(expr,var)- computes the indefinite integral of expr with respect to the symbolic scalar
variable var. Specifying the variable var is optional. If you do not specify it, int uses the default
variable determined by symvar. If expr is a constant, then the default variable is x.
• int(expr,var,a,b)- computes the definite integral of expr with respect to var from a to b.
If you do not specify it, int uses the default variable determined by symvar. If expr is a constant,
then the default variable is x.
syms x
int(cos(x)ˆ3,x)
ans =
sin(x) - sin(x)ˆ3/3
Example 7.2: Find the area bounded by the curve y = x2 + x + 2, x-axis and the ordinates x = 1, x = 2.
syms x y
y=xˆ2+x+2;
h=int(y,x,1,2)
h =
35/6
Exercise:
3x+5
R
1. Evaluate x2 −6x+12
dx.
dx
R
2. Evaluate a2 cos2 x+b2 sin2 x
.
syms y(t)
y(t) = dsolve(diff(y,t) == t*y)
y(t) =
C*exp(tˆ2/2)
Example 8.2: Solve the same ordinary differential equation with the initial condition y(0) = 2.
syms y(t)
y(t) = dsolve(diff(y,t) == t*y, y(0) == 2)
y(t) =
2*exp(tˆ2/2)
syms x(t)
x(t) = dsolve((diff(x,t) + x)ˆ2 == 1, x(0) == 0)
x(t) =
exp(-t) - 1
1 - exp(-t)
Example 8.4: An Aeroplane uses a parachute and other means of breaking as it slows down on the runway
after landing. Its acceleration is given by a = −0.0025v 2 − 9 m/s2 . Consider an aeroplane with a velocity
of 90 km/h that opens its parachute and starts decelerating at t = 0 s. By solving the differential equation
find the velocity.
[Hint: Take a = dv dt ]
syms v(t)
v(t) = dsolve(diff(v,t)== -0.0025*vˆ2-9, v(0) == 25)
v(t) =
-60*tan((3*t)/20 - atan(5/12))
Exercise:
R2019a
RV COLLEGE OF ENGINEERING ®
R. V. Vidyaniketan Post, Mysuru road
Tel: +91-80-67178021, 67178099 Fax: +91-80-67178011
www.rvce.edu.in