Numerical Method Lab Manual Matlab
Numerical Method Lab Manual Matlab
MGM
JAWAHARLAL NEHRU ENGINEERING COLLEGE
AURANGABAD
S.Y. B.TECH
DEPARTMENT OF
ELECTRICAL ELECTRONICS & POWER ENGINEERING
Vision of JNEC
To create self-reliant, continuous learner and competent technocrats imbued with human
values.
Mission of JNEC
1. Imparting quality technical education to the students through participative teaching –
learning process.
2. Developing competence amongst the students through academic learning and practical
experimentation.
3. Inculcating social mindset and human values amongst the students.
VISION:
MISSION:
Do’s
1. Know the location of the fire extinguisher and the first aid box and how to use them in
case of an emergency.
2. Read and understand how to carry out an activity thoroughly before coming to the
laboratory.
Don’ts
3. Do not open the system unit casing or monitor casing particularly when the power is
turned on. Some internal components hold high electric voltages which can be fatal.
4. Do not insert metal objects such as clips, pins and needles into the computer casings.
They may cause fire.
6. Do not touch, connect or disconnect any plug or cable without your lecturer/laboratory
technician’s permission. 7. Do not misbehave in the computer laboratory.
List of Experiments
Sr no Name of Experiment
Experiment no 1
1. INTRODUCTION:
The name MATLAB stands for Matrix Laboratory. The basic building block of MATLAB is
the matrix. It is not confined to the solution of Matrix related problems. With its inbuilt
functions, it is an excellent tool for linear algebraic computations, data analysis, signal
processing, optimization, numerical solutions of ordinary differential equations (ODE),
quadrature, 2D & 3D, graphics and many other types of scientific computation. Therefore,
we can say: MATLAB is a software package in high performance language for technical
computing. It integrates computation, visualization and programming in an easy to use
environment where problems and solutions are expressed in familiar mathematical
notation. Typical uses include:
Math and computation
Algorithm and development
Data acquisition modeling
Simulation and prototyping
Data analysis, exploration, and visualization
Scientific and engineering graphics
Application development, including graphical user interface building.
2. BASICS:
2.1 MATLAB WINDOWS: There are three basic window which are as follows:
1. MATLAB DESKTOP: This is the window which appears by default when MATLAB
is launched. It consists of :
COMMAND WINDOW: This is the main window , where command are written. It is
characterized by MATLAB command prompt (>>). The results also appear on this
window(except figures, which appear on figure window) which command is
written. Commands cannot be edited in this window.
CURRENT DIRECTORY: This appears on the bottom left side of MATLAB desktop.
It is where all files are listed. With a mouse right click, you can run M-files, rename,
delete them etc after selecting a file from here.
WORKSPACE: This sub-window shows all the variables generated so far and also
shows their type and size.
COMMAND HISTORY: All commands typed on the MATLAB prompt are recorded
here. Also commands can be selected from here and create as M-file. Thus it
remains records of MATLAB functions run.
2. FIGURE WINDOW:
The output of all the commands written on the command window or executed
by writing in M-file, whose output is a graph , appears on the window. The
user can create as many figure windows as the system memory allows. A
figure window is showing sine curve is shown in figure.
3. EDITOR WINDOW:
This is where we can write, create, edit and save programs in a file. The file is
known as M-file. To select editor window, go to file and then select M-file. The
programs written on the file are first saved and then run to get the results. To
save and run the program, go to debug and select ‘save and run’. The result
appear on the command window. The figure appear on the figure window. A
editor window is shown as in figure:
2.2 LANGUAGES:
MATLAB is a high-level language that includes matrix-based data structures,
its own internal data types, an extensive catalog of functions and scripts, the
ability to import and export to many types of data files, object-oriented
programming capabilities, and interfaces to external technologies such as
COM, Java, program written in C and Fortran, and serial port devices.
2.3 INPUT-OUTPUT:
MATLAB takes input from the screen and rushes output to the screen i.e. it
supports interactive computation. It can read input files and write output files.
2.3.1 Data Type: There is no need to declare a data to be real or complex.
When a real number is entered as a variable, MATLAB automatically sets the
variable to be real. Fundamental data type is the array.
2.3.2 Dimension: Dimension state is not required in the MATLAB. It is
automatic.
3. ACCESSORIES
3.1 TOOLBOXES: MATLAB features a family of add-on-application specific
solutions called toolboxes. Very important to most users of MATLAB,
toolboxes allow you to learn and apply specialized technology. Toolboxes are
comprehensive collections of MATLAB environment to solve particular classes
of problems. Areas in which toolboxes are available include signal processing,
control systems, neural networks, fuzzy logic, wavelets, simulation, and many
others. There are 78 toolboxes available. Thus we can say MATLAB basically
works as a platform and for solving a particular problem, concerned toolbox is
required. Few of the toolboxes are as follows:
Communication toolbox
Control system toolbox
Curve fitting toolbox
Data acquisition toolbox
Filter design toolbox
Fuzzy logic toolbox
Instrument control toolbox
Optimization toolbox
Statistics toolbox
Symbolic maths toolbox, etc.
Conclusion :
Experiment no 2
Theory :
Arrays and Vectors
An array is a collection of data objects of the same type, typically stored
sequentially in memory.
• An array is an elementary data structure.
• Almost all programming languages provide support for arrays.
• Matlab is a language that has been particularly specialized to support
arrays (and subsequently matrices).
• An array is the obvious way to represent a vector.
>> whos Name Size Bytes Class a 1x3 24 double array Grand total is 3
elements using 24 bytes
Operations on Arrays
• This process of constructing an array involves a segment of memory
being allocated and associated with the variable name, and the
elements of memory being set to the specified values.
• In most programming languages you would have to declare an array
and assign the values one at a time. In Matlab this is automatic.
• You can then perform arithmetic on arrays as simply as you can with
scalars. For example:
>> b = a*2 b = 2 5 10
Working with Array Elements
• You can extract individual values from an array by specifying the index
within the array using round brackets. For example:
>>c = b(1) % c is set to the value of the first element of b c = 2
• You can also assign new values to individual elements of an array. For
example:
mple: >> b(3) = 6 % Set the value of the 3rd element of b to 6
b=256
• In Matlab, the index of the first element of an array is always 1.
• Note: this differs from languages such a C or Java where the index of the
first element is always 0.
Matrices
• An array is a collection of data objects of the same type.
• The data objects of the array can themselves be arrays.
• A matrix is typically represented by an array of arrays, or a 2D array.
Matlab supports matrices in the same way that it supports vectors.
• Matlab uses the semi-colon (;) operator to distinguish between the
different rows of a matrix. For example:
Experiment no 3
SCAN CONVERTING LINES
Objective : TO study scan conversion of Line
Theory :
Description: Given the specification for a straight line, find the collection of
addressable pixels which most closely approximates this line.
The equation for a straight line: y = m * x + b, where m is the slope (m = dy/dx) and b
is the y intercept. So for a given x interval (dx) we can compute dy = m * dx, but this
is a brute force real number computation and is very slow.
So start with t = 0 and increment to t = 1.0, e.g. t= .05, .10,.15, etc. This is still too
slow but parametric equations are used for clipping, curve fitting, and ray tracing.
Let us assume a line of positive slope and draw from x1, y1 to x2, y2.
{slope = m = dy/dx}
if m <= 1.0 then
function draw(x0,y0,x1,y1)
clc
clear
point = input('Give coord[ x0 y0 x1 y1]: ');
x0 = point(1);y0 = point(2); x1 = point(3);y1=point(4);
dx = abs(x1-x0);
dy = abs(y1-y0);
sx = sign(x1-x0);
sy = sign(y1-y0);
if (dy > dx)
step = dy;
else
step = dx;
end
x(1) = x0; y(1) = y0; j = 1;
for i= 0:1:step
if (x1 == x)&(y1 == y)
break;
end
j = j+1;
x(j) = x(j-1) + (dx/step)*sx;
y(j) = y(j-1) + (dy/step)*sy;
end
plot(round(x),round(y),'rs');
grid on ,hold on
plot(x,y,'b^');
axis([point(1)-2 point(3)+2 point(2)-2 point(4)+2]);
legend('DDA Points','Actual points',2);
title('Digital Differential Line Drawing Algorithm')
Experiment no 4
SCAN CONVERTING CIRCLE
Objective : TO study scan conversion of Circle
Theory :
We use the above algorithm to calculate all the perimeter points of the circle
in the first octant and then print them along with their mirror points in the other
octants. This will work only because a circle is symmetric about it’s centre.
For any given pixel (x, y), the next pixel to be plotted is either (x, y+1) or (x-1,
y+1). This can be decided by following the steps below.
1. Find the mid-point p of the two possible pixels i.e (x-0.5, y+1)
2. If p lies inside or on the circle perimeter, we plot the pixel (x, y+1), otherwise
if it’s outside we plot the pixel (x-1, y+1)
Boundary Condition : Whether the mid-point lies inside or outside the circle
can be decided by using the formula:-
MATLAB PROGRAM
function h = circle(x,y,r)
Z=input('Enter the coordinates as [x,y] : ');
x = Z(1);
y = Z(2);
r = input('Enter the radius : ');
th = 0:pi/50:2*pi;
xunit = r * cos(th) + x;
yunit = r * sin(th) + y;
plot(xunit, yunit);
hold off
Experiment No 5
Scan convergence of Ellipse
Objective : Drawing ellipse using MATLAB script.
Theory : In mathematics, an ellipse is a curve in a plane surrounding two focal points such that the sum
of the distances to the two focal points is constant for every point on the curve. As such, it is a
generalization of a circle, which is a special type of an ellipse having both focal points at the same
location. The elongation of an ellipse is represented by its eccentricity, which for an ellipse can be any
number from 0 (the limiting case of a circle) to arbitrarily close to but less than 1.
Ellipses are the closed type of conic section: a plane curve resulting from the intersection of a
cone by a plane (see figure to the right). Ellipses have many similarities with the other two forms of conic
sections: parabolas and hyperbolas, both of which are open and unbounded. The cross section of a
cylinder is an ellipse, unless the section is parallel to the axis of the cylinder.
Analytically, an ellipse may also be defined as the set of points such that the ratio of the distance
of each point on the curve from a given point (called a focus or focal point) to the distance from that same
point on the curve to a given line (called the directrix) is a constant. This ratio is the above-mentioned
eccentricity of the ellipse
Definition of an ellipse as locus of points
An ellipse can be defined geometrically as a set of points (locus of points) in the Euclidean plane:
An ellipse is a curve that is the locus of all points in the plane the sum of whose distances
and from two fixed points and (the foci) separated by a distance of is a
given positive constant .This results in the two-center bipolar coordinate equation
where a is the semimajor axis and the origin of the coordinate system is at one of the foci. The
corresponding parameter b is known as the semiminor axis.
The ellipse is a conic section and a Lissajous curve.
An ellipse can be specified in the Wolfram Language using Circle[{x, y}, {a, b}].
If the endpoints of a segment are moved along two intersecting lines, a fixed point on the segment (or on
the line that prolongs it) describes an arc of an ellipse. This is known as the trammel construction of an
ellipse (Eves 1965, p. 177).
Let an ellipse lie along the x-axis and find the equation of the figure (1) where and are
at and . In Cartesian coordinates,
Bring the second term to the right side and square both sides,
Conclusion :
MATLAB Program
a=input('Enter Horizontal radius : '); % horizontal radius
b=input('Enter Vertical radius : '); % vertical radius
Z=input('Enter the centere coordinates as [x,y] : ');
x0=Z(1); % x0,y0 ellipse centre coordinates
y0=Z(2);
t=-pi:0.01:pi;
x=x0+a*cos(t);
y=y0+b*sin(t);
plot(x,y,'r')
hold on
plot(x0,y0,'or');
grid on
title('Scan Convergence of Ellip')
xL = xlim;
yL = ylim;
line([0 0], yL); %y-axis
line(xL, [0 0]); %x-axis
hold off
Experiment No 6
Scan convergence of Rectangle & Square
Objective : Drawing rectangle/square using MATLAB script.
Theory : In Euclidean plane geometry, a rectangle is a quadrilateral with four right angles. It can also
be defined as an equiangular quadrilateral, since equiangular means that all of its angles are equal
(360°/4 = 90°). It can also be defined as a parallelogram containing a right angle. A rectangle with
four sides of equal length is a square. The term oblong is occasionally used to refer to a non-square
rectangle. A rectangle with vertices ABCD would be denoted as Rectanglen.PNG ABCD.
The word rectangle comes from the Latin rectangulus, which is a combination of rectus (as an
adjective, right, proper) and angulus (angle).
Rectangles are involved in many tiling problems, such as tiling the plane by rectangles or
tiling a rectangle by polygons.
Characterizations
A convex quadrilateral is a rectangle if and only if it is any one of the following:[5][6]
Classification
A rectangle is a special case of both parallelogram and trapezoid. A square is a special case of a rectangle.
Traditional hierarchy
A rectangle is a special case of a parallelogram in which each pair of adjacent sides is perpendicular.
A parallelogram is a special case of a trapezium (known as a trapezoid in North America) in
which both pairs of opposite sides are parallel and equal in length.
A trapezium is a convex quadrilateral which has at least one pair of parallel opposite sides.
A convex quadrilateral is
Conclusion :
Experiment No 7
McLaurin Series
Objective : Drawing ellipse using MATLAB script
Theory :
Conclusion :
Experiment No 8
Bisection method
Theory :
There are various methods available for finding the roots of given equation such
as Bisection method, False position method, Newton-Raphson method, etc.
Today I am going to explain Bisection method for finding the roots of given
equation. I will also explain MATLAB program for Bisection method.
Bisection method is very simple but time-consuming method. In this method,
we first define an interval in which our solution of the equation lies. As the
name indicates, Bisection method uses the bisecting (divide the range by 2)
principle. In this method, we minimize the range of solution by dividing it by
integer 2.
Following are the steps to find the approximate solution of given equation using
Bisection method:
Let us assume that we have to find out the roots of f(x), whose solution lies in
the range (a,b), which we have to determine. The only condition for bisection
method is that f(a) and f(b) should have opposite signs (f(a) negative and f(b)
positive). When f(a) and f(b) are of opposite signs at least one real root between
‘a’ and ‘b’ should exist.
x0=(a+b)/2
MATLAB PROGRAM
function p = bisection(f,a,b)
% provide the equation you want to solve with R.H.S = 0
form.
% Write the L.H.S by using inline function
% Give initial guesses.
% Solves it by method of bisection.
% A very simple code. But may come handy
if f(a)*f(b)>0
disp('Wrong choice bro')
else
p = (a + b)/2;
err = abs(f(p));
while err > 1e-7
if f(a)*f(p)<0
b = p;
else
a = p;
end
p = (a + b)/2;
err = abs(f(p));
end
end
Experiment No 9
Simpsons 1/3 Rule for Inegration
Theory :
This function computes the integral "I" via Simpson's rule in the interval [a,b]
with n+1 equally spaced points
Syntax: I = simpsons(f,a,b,n)
Where,
f= can either be an anonymous function (e.g. f=@(x) sin(x)) or a vector
containing equally spaced values of the function to be integrated
a= Initial point of interval
b= Last point of interval
n= # of sub-intervals (panels), must be integer
Example 1:
Example 2:
Program in MATLAB
function I = simpsons(f,a,b,n)
% This function computes the integral "I" via Simpson's rule in the
interval [a,b] with n+1 equally spaced points
%
% Syntax: I = simpsons(f,a,b,n)
%
% Where,
% f= can be either an anonymous function (e.g. f=@(x) sin(x)) or a vector
% containing equally spaced values of the function to be integrated
% a= Initial point of interval
% b= Last point of interval
% n= # of sub-intervals (panels), must be integer
%
% Written by Juan Camilo Medina - The University of Notre Dame
% 09/2010 (copyright Dr. Simpson)
%
%
% Example 1:
%
% Suppose you want to integrate a function f(x) in the interval [-1,1].
% You also want 3 integration points (2 panels) evenly distributed through
the
% domain (you can select more point for better accuracy).
% Thus:
%
% f=@(x) ((x-1).*x./2).*((x-1).*x./2);
% I=simpsons(f,-1,1,2)
%
%
% Example 2:
%
% Suppose you want to integrate a function f(x) in the interval [-1,1].
% You know some values of the function f(x) between the given interval,
% those are fi= {1,0.518,0.230,0.078,0.014,0,0.006,0.014,0.014,0.006,0}
% Thus:
%
% fi= [1 0.518 0.230 0.078 0.014 0 0.006 0.014 0.014 0.006 0];
% I=simpsons(fi,-1,1,[])
%
% note that there is no need to provide the number of intervals (panels)
"n",
% since they are implicitly specified by the number of elements in the
% vector fi
if numel(f)>1 % If the input provided is a vector
n=numel(f)-1; h=(b-a)/n;
I= h/3*(f(1)+2*sum(f(3:2:end-2))+4*sum(f(2:2:end))+f(end));
else % If the input provided is an anonymous function
h=(b-a)/n; xi=a:h:b;
I= h/3*(f(xi(1))+2*sum(f(xi(3:2:end-
2)))+4*sum(f(xi(2:2:end)))+f(xi(end)));
end
Experiment No 10
Newton Rapson Method
Objective : Writing Code for Newton Rapson method
Theory :
This article is about Newton's method for finding roots. For Newton's method for finding minima, see
Newton's method in optimization.
In numerical analysis, Newton's method (also known as the Newton–Raphson method), named after
Isaac Newton and Joseph Raphson, is a method for finding successively better approximations to the
roots (or zeroes) of a real-valued function. It is one example of a root-finding algorithm.
The method starts with a function f defined over the real numbers x, the function's derivative f ′, and
an initial guess x0 for a root of the function f. If the function satisfies the assumptions made in the
derivation of the formula and the initial guess is close, then a better approximation x1 is
Geometrically, (x1, 0) is the intersection of the x-axis and the tangent of the graph of f at (x0, f (x0)).
This algorithm is first in the class of Householder's methods, succeeded by Halley's method. The
method can also be extended to complex functions and to systems of equations.
Program :