0% found this document useful (0 votes)
1K views34 pages

Matlab Manual Engineering Maths II

Uploaded by

Advaith Shetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views34 pages

Matlab Manual Engineering Maths II

Uploaded by

Advaith Shetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Rashtreeya Sikshana Samithi Trust

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

2 Elementary Math Built-In Functions 8

3 Plotting of Standard Cartesian Curves and Polar Curves 13

4 Statistics – Measures of Central Tendency and Dispersion 20

5 Plotting Statistical Data 22

6 Differentiation 29

7 Integration 31

8 First Order Differential Equations 32

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.

How to access MATLAB R2019a


The next two sections outline instructions on obtaining access to MATLAB. You will first need to associate
to the RVCE MATLAB Campus-Wide License and then install MATLAB.
Associate to the Campus-Wide License :

1. Open the RVCE MATLAB Portal or simply scan the QR Code

2. Click on Sign-In to get started.

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

RV College of Engineering 3 Enjoy Learning...


Experiential Learning Department of Mathematics

To Download the Software:


1. Click the download button for the current release. (Users can also download previous releases here).

2. Choose a supported platform and download the installer.

3. Run the installer.

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.

6. Select the products you want to download and install.

7. After downloading and installing your products, keep the Activate MATLAB checkbox selected and
click Next.

8. Select “Activate automatically using the internet”.

9. Log into your MathWorks account

10. Select the Academic Total Headcount license labeled Individual.

11. Click “finish” to complete the activation process.

Will MATLAB run on all computers?


Supported Hardware and Operating Systems
• Operating System Requirement: MATLAB R2016a is supported by 64-bit Windows, Mac OS X
and Linux operating systems. These include Windows 10, Windows 8.1, Windows 8, Windows 7 SP1,
Mac OS X 10.11 (El Capitan), Mac OS X 10.10 (Yosemite), Ubuntu 14.04 LTS through 15.10, Red
Hat Enterprise Linux 6 and 7, SUSE Linux Enterprise Desktop 11 and 12, and Debian 7.x, 8.x.

• Processor requirement: Any Intel or AMD x86-64 processor

• RAM requirement: Minimum 2GB. However 4GB RAM is recommended.

• Disk Space requirement: 2GB for MATLAB only. However, a disk space of 4-6 GB is recom-
mended.

How to start MATLAB?


One can enter MATLAB by double-clicking on the MATLAB shortcut icon on Windows desktop. When
MATLAB is started, a special window called the MATLAB desktop appears which consists of following
sub-windows:
Command Window- This is the main part of the window where commands can be entered. It is indicated
by the command prompt (>>).
Current Folder- The files created in MATLAB are saved in current directory. The saved files can be viewed
and accessed for further use.
Workspace- The workspace shows all the variables created and/or imported from files and displays type
and size of the variables.

RV College of Engineering 4 Enjoy Learning...


Experiential Learning Department of Mathematics

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.

Figure : MATLAB Desktop

How to open and save files?


In the toolbar of MATLAB window, the options ‘HOME’ or ‘EDITOR/LIVE EDITOR’ possess the icon
which is to ‘open’ a file with ‘.m’ or ‘.mlx’ extension. The particular file gets loaded in editor window
once it is clicked on. All DOS commands are also applicable. A click on the icon saves the file.

Symbolic Math Toolbox


Symbolic Math Toolbox provides functions for solving and plotting symbolic math equations. One can
create, run and share symbolic math code using the MATLAB Live Editor. The toolbox provides libraries of
functions in common mathematical areas such as calculus, linear algebra, algebraic and ordinary differential
equations, equation simplification and equation manipulation.
Symbolic Math Toolbox lets analytically perform differentiation, integration, simplification, transforms, and
equation solving. Computations can be performed either analytically or using variable precision arithmetic,
with the results displayed in mathematical typeset. It is possible to share the symbolic work as live scripts
with other MATLAB users or convert them to HTML or PDF for publication. MATLAB functions, Simulink
function blocks, and Simscape equations can be generated directly from symbolic expressions.

RV College of Engineering 5 Enjoy Learning...


Experiential Learning Department of Mathematics

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.

Arithmetic Operators and Special Characters


Operations Symbol Examples Operations Symbol Examples
Addition + 4+3=7 Right division / 1/2
Subtraction − 5−3=2 Left division \ 4\8 = 8/4 = 2
Multiplication ∗ 6 ∗ 7 = 42 Exponentiation ˆ 53 = 125

Some mathematical symbols:


p
1. pi - π 2. Inf - ∞ 3. i(or j) - ( − 1)

Syntax and description:

• 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:

Evaluate the following:

RV College of Engineering 6 Enjoy Learning...


Experiential Learning Department of Mathematics

35 ( 7/2−1) 1+2i
1. 25 −1
. 2. 3 (2/3−4)2
−2. 3. 2−3i . 4. (2 + 7i)(3 − 5i) + 72 i − 67 i .

5. Multiply 3 by 8, divide this product by the difference between 13 & 7.

RV College of Engineering 7 Enjoy Learning...


Experiential Learning Department of Mathematics

2 Elementary Math Built-In Functions


Topic learning outcomes:
Student will be able to:
1. Demonstrate elementary math functions such as algebraic, trigonometric, logarithmic, exponential and
complex valued functions using symbolic math.
2. Create and work with arrays.
3. Calculate the value of functions at different points.

Syntax and description:

sin - Sine

sind - Sine of argument in degrees

sinh - Hyperbolic sine

asin - Inverse sine

asind - Inverse sine, result in degrees

asinh - Inverse hyperbolic sine

cos - Cosine

tan - Tangent

sec - Secant

csc - Cosecant

cot - Cotangent

exp - Exponential

log - Natural logarithm

log10 - Common (base 10) logarithm

sqrt - Square root

ab - Absolute value

imag - Complex imaginary part

real - Complex real part

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.

RV College of Engineering 8 Enjoy Learning...


Experiential Learning Department of Mathematics

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.

Syntax and description:


• syms var1 ... varN - creates symbolic variables var1 ... varN. Separate variables by
spaces.
Note: Semicolon (;) at the end of the command suppress the screen output.
Example 2.1: Assign a=2, b=3 and find addition of a and b, difference of a and b, product of a and b,
division of b by a, sine of a, exponential of a, product of tangent of a and b.
a=2;
b=3;
a+b
a-b
a*b
b/a
sin(a)
exp(a)
b*tan(a)

ans =
5
ans =
-1
ans =
6
ans =
1.5000
ans =
0.9093
ans =
7.3891
ans =
-6.5551

Example 2.2: Find real and imaginary part of x + iy.


syms x y real % defines x, y as symbollic variables
f = x+i*y;
imag(f)
real(f)

RV College of Engineering 9 Enjoy Learning...


Experiential Learning Department of Mathematics

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)

Example 2.4: Find imaginary and real part of function e(x+iy) .


syms x y real
h=exp(x+i*y);
imag(h)
real(h)

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).

Syntax and description:


• [x1 x2 x3 ....] or [x1,x2,x3,...]- returns a row vector, assigning discrete values.
• [x1;x2;x3 ....]- returns column vector, assigning discrete values.
• variable name = [x1: spacing : x2]- generates continuous values with equal spac-
ing.
• variable name = [x1 : x2] - generates continuous values with default spacing 1.
• variable name = linspace(x1, x2) - returns a row vector of 100 evenly spaced points
between x1 and x2.
• variable name = linspace(x1, x2, n)- generates n points. The spacing between the
points is (x2-x1)/(n-1).

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.

RV College of Engineering 10 Enjoy Learning...


Experiential Learning Department of Mathematics

Arithmetic array operators


Operator Purpose Description
+ Addition A + B adds A and B
+ Unary plus +A returns A
− Subtraction A − B subtracts B from A
− Unary minus −A negates the elements of A
.∗ Element-wise multiplication A. ∗ B is the element-by-element product of A and B
.ˆ Element-wise power A.ˆB is the matrix with elements A(i, j) to the B(i, j) power
./ Right array division A./B is the matrix with elements A(i, j)/B(i, j)
.0 Array transpose A.0 is the array transpose of A.

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

Example 2.6: Assign discrete values 5, 2, 1, 6, 7 to a variable x.

x=[5 2 1 6 7]

x =
5 2 1 6 7

Example 2.7: Assign continuous integral values from 1-5 to a variable x.

x=[1:5]

x =
1 2 3 4 5

Example 2.8: Generate numbers between -3 & 9 with spacing 2.

y=[-3:2:9]

y =
-3 -1 1 3 5 7 9

RV College of Engineering 11 Enjoy Learning...


Experiential Learning Department of Mathematics

Example 2.9: Generate 5 values between 0 to 25 with equal divisions.

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.

x=[1,5,-7,1/2]; % Assigns the values 1, 5, -7, 1/2 to x as row vector.


y=((x.ˆ2-1)./(2.*x+3)) % Assigns the given expression to a variable ’y’.

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 γ.

3. Find the distance between the points (2,4,6) and (1,2,3).

4. Calculate the radius ‘r’ of a sphere that has a volume of 350 inch3 .

RV College of Engineering 12 Enjoy Learning...


Experiential Learning Department of Mathematics

3 Plotting of Standard Cartesian Curves and Polar Curves


Topic learning outcomes:
Using MATLAB student will be able to:
1. Plot two dimensional Cartesian and polar curves.
2. Set the line style, marker symbol, color, label axes with text strings and title the graph with a text string
in graphs.
3. Plot multiple curves in one graph.

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

RV College of Engineering 13 Enjoy Learning...


Experiential Learning Department of Mathematics

Colors and their codes for curve:

Code Color Code Color


w White k Black
b Blue r Red
c Cyan g Green
m Magenta y Yellow

Commands for labeling along the x-axis and y-axis, adding title and grid lines

• xlabel(’name’) - generate labels along x-axis.


• ylabel(’name’) - generate labels along y-axis.
• title(’name’) - allows to put a title on the graph.
• grid on - allow to put the grid lines on the graph.

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)

RV College of Engineering 14 Enjoy Learning...


Experiential Learning Department of Mathematics

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.

RV College of Engineering 15 Enjoy Learning...


Experiential Learning Department of Mathematics

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)’)

2-D Line Plot


1

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

Example 3.5: Plot the graph of strophoid given by y 2 (2 − x) = x2 (2 + x) for -2<x<2.

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

RV College of Engineering 16 Enjoy Learning...


Experiential Learning Department of Mathematics

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.

Example 3.6: Plot the curve r = 2 sin 3θ(three leaved rose).

syms r theta
theta = 0:0.01:2*pi;
r = 2*sin(3*theta);
polarplot(theta,r)

RV College of Engineering 17 Enjoy Learning...


Experiential Learning Department of Mathematics

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)

RV College of Engineering 18 Enjoy Learning...


Experiential Learning Department of Mathematics

90
6
120 60

4
150 30

180 0 0

210 330

240 300
270

Exercise:

1. Draw the graph of the curve y = x3 + 2x + 3.

2. Generate the plot of the curve y = e−2x sin(2x).

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θ).

4. Plot the graph of the curve r2 = 4 cos(2θ).

RV College of Engineering 19 Enjoy Learning...


Experiential Learning Department of Mathematics

4 Statistics – Measures of Central Tendency and Dispersion


Topic learning outcomes:
Student will be able to:
1. Evaluate mean, median, mode, variance and standard deviation from array
2. Import data from the excel file to obtain mean, mode, variance and standard deviation

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.

Syntax and description:

mean - Average or mean value of array

median - Returns the median value of array.

mode - Most frequent values in array

std - 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

RV College of Engineering 20 Enjoy Learning...


Experiential Learning Department of Mathematics

ans =
4.5000
ans =
2.8884
ans=
1.6995

Import Data from Spreadsheets

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.

RV College of Engineering 21 Enjoy Learning...


Experiential Learning Department of Mathematics

5 Plotting Statistical Data


Topic learning outcomes:
Student will be able to:
1. Create bar graphs and pie charts for set of data.
2. Draw the bars with labels, set the relative bar width, specify the style of the bar groups and set the color
for all the bars.
3. Draw multiple pie chart with labels.

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

RV College of Engineering 22 Enjoy Learning...


Experiential Learning Department of Mathematics

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.

No. of places visited by Day 1 Day 2 Day 3 Day 4


Person 1 2 2 2 2
Person 2 1 5 8 11
Person 3 3 7 9 12

Display four groups of three bars.

y = [2 1 3; 2 5 7; 2 8 9; 2 11 12];
bar(y)

RV College of Engineering 23 Enjoy Learning...


Experiential Learning Department of Mathematics

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

RV College of Engineering 24 Enjoy Learning...


Experiential Learning Department of Mathematics

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.

RV College of Engineering 25 Enjoy Learning...


Experiential Learning Department of Mathematics

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].

X=[1 3 0.5 2.5 2];


Y=[0.1 0.3 0.2 0.25 0.15];
Z=[0.2 0.15 0.05 0.3];
pie(X)
pie(Y)
pie(Z)

RV College of Engineering 26 Enjoy Learning...


Experiential Learning Department of Mathematics

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)

Example 5.8: Accounts data of a company are given below:


Taxes ( % ) Expenses ( % ) Profit ( % )
2014 20 40 40
2015 24 46 30

RV College of Engineering 27 Enjoy Learning...


Experiential Learning Department of Mathematics

Draw multiple pie chart.


X = [20 40 40];
labels = {’Taxes’,’Expenses’,’Profit’};
ax1 = subplot(1,2,1);
pie(ax1,X,labels)
title(ax1,’2014’);

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:

Week First Second Third Fourth Fifth


Number of cars produced 800 1300 1060 920 1440

Create bar graph in green color.

2. The following table shows the export earnings of India (in crores) during five consecutive years:

Year 2010 2011 2012 2013 2014


Spices export 120 125 132 146 150
Handicrafts export 100 107 110 118 130
Books export 102 115 121 132 142
Display data in five groups of three bars.

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.

RV College of Engineering 28 Enjoy Learning...


Experiential Learning Department of Mathematics

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.

Differentiate symbolic expression or function


Syntax and description:


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)

RV College of Engineering 29 Enjoy Learning...


Experiential Learning Department of Mathematics

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)

Therefore the acceleration is always equal to displacement.

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.

RV College of Engineering 30 Enjoy Learning...


Experiential Learning Department of Mathematics

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.

Syntax and description:

• 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.

Note:int(expr,var,[a,b]), int(expr,var,[a b]), and int(expr,var,[a;b]) are


equivalent to int(expr,var,a,b).

Example 7.1: Integrate cos3 x with respect to 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
.

3. Find the area of the region bounded by y = 2x − x2 and x− axis.


π 3π
4. Calculate area enclosed by the curve y = sin(2x), x-axis and the lines x = 4 and x = 4 .

RV College of Engineering 31 Enjoy Learning...


Experiential Learning Department of Mathematics

8 First Order Differential Equations


Topic learning outcomes:
Using MATLAB student will be able to:
1. Find the general and particular solution of first order ordinary differential equations.
2. Solve application problems such as finding current in RL circuit, obtaining equation of the orthogonal
trajectory.

Syntax and description:

• dsolve(diff(y,x)==f(x,y)) - solves the ordinary differential equation.


• dsolve(diff(y,x)==f(x,y,condition)) - solves the ordinary differential equation with
the initial or boundary condition.

Linear differential equations


Example 8.1: Solve y 0 = ty.

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)

Nonlinear differential equations


Nonlinear equations can have multiple solutions, even if you specify initial conditions.

Example 8.3: Solve ( dx 2


dt + x) = 1

syms x(t)
x(t) = dsolve((diff(x,t) + x)ˆ2 == 1, x(0) == 0)

x(t) =
exp(-t) - 1
1 - exp(-t)

RV College of Engineering 32 Enjoy Learning...


Experiential Learning Department of Mathematics

This resulted in two solutions.

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:

1. Solve ydx + 2xdy = 0.


dy
2. The slope at any point of a curve y = f (x) is given by dx = 3x2 and it passes through (-1,1). Find the
equation of the curve.
dy a2 −x2
3. The differential equation of the orthogonal trajectory is dx = xy . Find the equation of that orthogonal
trajectory.

4. For the RL circuit L dI


dt + RI = E(t). Find the current at any time t > 0 having a constant electromotive
force 40 V, a resistor 10 ohm and an inductor 0.2 H given that initial current is zero.

Published with MATLAB


R

R2019a

RV College of Engineering 33 Enjoy Learning...


DEPARTMENT OF MATHEMATICS
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.
Rashtreeya Sikshana Samithi Trust

RV COLLEGE OF ENGINEERING ®
R. V. Vidyaniketan Post, Mysuru road
Tel: +91-80-67178021, 67178099 Fax: +91-80-67178011
www.rvce.edu.in

You might also like