22MA21B Matlab Manual
22MA21B Matlab Manual
22MA21B Matlab Manual
RV COLLEGE OF ENGINEERING®
(Autonomous Institution Affiliated to VTU, Belagavi)
DEPARTMENT OF MATHEMATICS
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
3 Numerical Integration 14
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.
3 Numerical Integration
Topic learning outcomes:
Student will be able to:
Evaluate definite integrals when
R 0.6 2
Example 3.1. Evaluate 0 e−x dx.
q = integral(fun,0,0.6)
p = quadgk(fun,0,0.6)
q =
0.5352
p =
0.5352
Example 3.2. A solid of revolution is formed by rotating about the x−axis, the area between the x−axis,
the lines x = 0 and x = 1 and a curve through the point with the following coordinates.
R1
Estimate the volume of the solid formed. Hint: Required volume = 0 πy 2 dx.
x = 0.00:0.25:1;
y = [1.0000 0.9896 0.9589 0.9089 0.8415];
Y = y.ˆ2;
V = pi*trapz(x,Y)
V =
2.8109
Example 3.3. A rocket is launched from the ground. Its acceleration is registered during the first 80
seconds and is given in the table. Find the velocity of the rocket at t = 80s.
t: 0 10 20 30 40 50 60 70 80
a: 30 31.63 33.34 35.47 37.75 40.33 43.25 46.69 50.67
R 80
Hint: Velocity = 0 adt.
x = 0:10:80;
y = [30 31.63 33.34 35.47 37.75 40.33 43.25 46.69 50.67];
Q = trapz(x,y)
Q =
3.0879e+03
Numerical Integration: User defined functions for Trapezoidal rule, Simpson’s 1/3 rule and Simp-
son’s 3/8 rule.
Trapezoidal Rule
Rb
a ydx = h2 [y0 + 2(y1 + y2 + ... + yn−1 ) + yn ],
where
h = (b−a)
n
i.e., the interval [a, b] is divided into n sub-intervals. Note that the indexing in MATLAB starts from 1
and the last term in an array can be referred to using the index ’end’. We will need to modify the formula
while implementing to ensure that the indexing is correct, i.e., 0 is replaced by 1, 1 by 2 and so on and n is
replaced by ’end’.
I_trap = h/2*(y(1)+2*(sum(y(2:end-1)))+y(end))
I_simp13 = h/3*(y(1)+2*(sum(y(3:2:end-2)))+4*(sum(y(2:2:end-1)))+y(end))
I_simp38 = (3/8)*h*(y(1)+y(end)+2*(sum(y(4:3:end-3)))+3*(sum(y(2:end-1))...
-sum(y(4:3:end-3))))
x = [4.0,4.2,4.4,4.6,4.8,5.0,5.2];
y = [1.3863,1.4351,1.4816,1.5261,1.5686,1.6094,1.6487];
h = (5.2-4)/(length(x)-1);
I_trap = h/2*(y(1)+2*(sum(y(2:end-1)))+y(end))
I_trap =
1.8277
q = trapz(x,y)
q =
1.8277
I_simp13 = h/3*(y(1)+2*(sum(y(3:2:end-2)))+4*(sum(y(2:2:end-1)))+y(end))
I_simp13 =
1.8279
I_simp38 = (3/8)*h*(y(1)+y(end)+2*(sum(y(4:3:end-3)))+3*(sum(y(2:end-1))...
-sum(y(4:3:end-3))))
I_simp38 =
1.8278
Exercise:
R π/2 √
1. Evaluate 0 cos θdθ.
R 1.4
2. Evaluate 0.2 (sin x − log x + ex )dx.
3. A river is 80 feet wide. The depth d in feet at a distance x feet from one bank is given by:
x: 0 10 20 30 40 50 60 70 80
d: 0 4 7 9 12 15 14 8 3
4. A body of weight w tons is acted upon by a variable force F tons weight. It acquires a speed of v
mph after travelling y yards where v 2 = 89.8
R
w F (y)dy. If w = 600 and F is given by the table
below, estimate the velocity at the end of 400 yards from the starting point.
1. Find the value of function (dependent variable) at different values of independent variable by numer-
ically solving the differential equation.
Note: Stiff differential equation - A differential equation of the form y 0 = f (t, y) is said to be stiff if its
exact solution y(t) includes a term that decays exponentially to zero as t increases, but whose derivatives
are much greater in magnitude than the term itself. An example of such a term is e−ct , where c is a large,
positive constant, because its k th derivative is ck e−ct . Because of the factor of ck , this derivative decays to
zero much more slowly than e−ct as t increases. Because the error includes a term of this form, evaluated
at a time less than t, the error can be quite large if h is not chosen sufficiently small to offset this large
derivative. Furthermore, the larger c is, the smaller h must be to maintain accuracy.
dy
Example 4.1. Solve the initial value problem dx = 2y + 3ex , y(0) = 0 for x = 0.1, 0.2, 0.3.
xspan = [0:0.1:0.3];
y0 = 0;
[x,y] = ode45(@(x,y) 2*y+3*exp(x), xspan, y0)
x =
0.1000
0.2000
0.3000
y =
0
0.3487
0.8113
1.4168
dy
Example 4.2. Solve the initial value problem dt = t2 y − 1, y(0) = 1 for t = 0.1 to 0.4.
tspan = [0:0.1:0.4];
y0 = 1;
[t,y] = ode23(@(t,y) tˆ2*y-1, tspan, y0)
plot(t,y,’-o’)
t =
0
0.1000
0.2000
0.3000
0.4000
y =
1.0000
0.9003
0.8023
0.7070
0.6151
0.9
0.8
y 0.7
0.6
0 0.1 0.2 0.3 0.4
t
Example 4.3. A 1500 gallon tank initially contains 600 gallons of water with 5 lbs of salt dissolved in it.
Water enters the tank at a rate of 9 gallon per hour and the water entering the tank has a salt concentration
of 51 (1 + cos t) lbs/gal. If a well mixed solution leaves the tank at a rate of 6 gal/hr. If amount of salt at any
time t is Q(t) then the IVP for this situation is dQ 2Q 9
dt + 200+t = 5 (1 + cos t), Q(0) = 5 and it overflows at t
= 300 hrs. How much salt is in the tank when it overflows?
tspan = [0:150:300];
Q0 = 5;
[t,Q] = ode23(@(t,Q) (9*(1+cos(t))/5)-2*Q/(200+t), tspan, Q0)
t =
0
150
300
Q =
5.0000
171.1931
279.8302
This circuit can also be transformed into a parallel RLC circuit with a current source IS .
The voltage across the inductor and the capacitor are equal.
VL (t) = VC (t)
L dIdtL = VC (t)
dIL 1
dt = L VC (t)
IS = IR + IL + IC
Rearranging:
IC + IL + IR − IS = 0
C dVdtC + IL + VC
R − IS = 0
dVC IS IL VC
dt = C − C − RC
Implementing this in a function RLC (found below) which is used in the following script:
t0 = 0; %Start Time
tf = 0.001; %Stop Time
x0 = [0 20]; %Initial Conditions for Capacitance Voltage and Inductor Curr
20
-20
-40
0 0.2 0.4 0.6 0.8 1
Time × 10-3
This function provides the xdot parameter for a second order RLC circuit
t is the time x is the initial condition (Capacitance voltage and inductor current) x is a 2 element vector -
x(1) is the capacitor voltage and x(2) is the inductor current
% Source Current
Is = 2;
%RLC values
R = 100;
L = 1e-3;
C = 1e-6;
%Calculating dx1/dt and dx2/dt and putting them into a column vector
xdot(1) = 1/L * x(2);
xdot(2) = 1/C * Is - 1/C*x(1) - 1/(R*C)*x(2);
xdot = xdot’;
end
Simple Pendulum
The equation of oscillation of a simple pendulum is given by:
d2 θ −g
dt2
= L sin θ
We will use the built-in function ode45 to solve the equation after setting up the differential equation in
the above form.
1.5
0.5
-0.5
-1
-1.5
-2
0 10 20 30 40 50
Exercise:
dy t3 −2y
1. Solve dt = t ,1 ≤ t ≤ 3 with y = 4.2 at t = 1.
2. An aeroplane uses a parachute and other means of braking as it slows down on the runway after
landing. Its acceleration is given by a = −0.0045v 2 − 3m/s2 . Since a = dv
dt , the rate of change of
4. The number N of bacteria in a culture grew at a rate proportional to N. The value of N was initially
100 and increased to 332 in 1 hr. The governing equation is dN
dt = log(3.32)N, N (0) = 100. What
is the value of N at time t = 1.5 hr.
Example 5.1. Find all the roots of the equation x4 + 2x2 − 16x + 5 = 0.
syms x
vpasolve(xˆ4+2*xˆ2-16*x+5 == 0, x)
ans =
0.32653906234460422084857323401358
2.1111516462471155473107246160362
- 1.2188453542958598840796489250249 - 2.4015366984564279025134418606114i
- 1.2188453542958598840796489250249 + 2.4015366984564279025134418606114i
Example 5.2. Determine the root of the equation x2 − log x = 12 in (3, 4).
ans =
3.6460448399001736218717213181561
Example 5.3. The volume V of liquid in a spherical tank of radius r is related to the depth h of the liquid
2
by V = πh (3r−h)
3 . Obtain the roots of equation which give height h to which the dipstick immersed is wet
with liquid, given r = 1m and V = 0.5 m3 .
syms h
vpasolve(hˆ3-3*hˆ2+0.4775 == 0, h)
ans =
-0.37608006988252444956702991370319
0.43113799780627533182088418262644
2.9449420720762491177461457310768
Here radius of spherical tank is 1m, hence diameter = 2m. Therefore h = 0.4311m is the only possibility
for the given physical situation.
Example 5.4. The bacteria concentration c in a reservoir varies as t4 − t = c. Calculate the time t
required for the bacteria concentration to be c = 10, given that initial time is t = 2s.
syms t
vpasolve(tˆ4-t-10 == 0,t,[1,2.5])
ans =
1.855584528640937863760250564888
Exercise:
3. The current i in an electric circuit is given by i = 10e−t sin(2πt), where t is in seconds. Find the
value of t for i = 2 amp.
4. Water is falling in a trapezoidal channel at a rate of Q = 20m3 /s. The critical depth y for such a
2
channel must satisfy the equation 1 − QgAB3 = 0 where g = 9.81m/s2 , A is the cross sectional area
in m2 and B is the width of the channel at surface in m. For this case width and cross-sectional area
2
can be related to depth y by B = 3 + y and A = 3y + y2 . Solve it for critical depth.
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.
var - Variance
Example 6.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 6.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.
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.
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 7.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 7.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 7.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 7.4. In Example 7.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 7.5. Production of two items in three months are given below:
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.
1. 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
2. If sum(X) > 1, then pie normalizes the values by X/sum(X) to determine the area of each slice
of the pie.
3. 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 7.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 7.7. The marks obtained by a student in his annual examination are given below:
X=[90 75 72 58 63];
labels = {’Maths’,’Electronics’,’Civil’,’Computer’,’Physics’};
pie(X,labels)
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:
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:
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