Digital Simulation Lab-1
Digital Simulation Lab-1
BY
ALLABAKSHU SHAIK
Head Of The Department
Aeronautical Engineering
Allabakshu Shaik 2
Digital Simulation Lab-1
CONTENTS
1. Introduction to CFD
2. Introduction to FLUENT and GAMBIT
3. SIMULATION OF FLOW PAST OVER A 2D AIRFOIL
4. SIMULATION OF FLOW OVER 3D WING
5. SIMULATION OF COMPRESSIBLE FLOW IN A CONVERGENTDIVERGENT NOZZLE
6. INTRODUCTION TO MAT LAB
7.
3
9
10
18
26
34
Allabakshu Shaik 3
Digital Simulation Lab-1
1. INTRODUCTION TO CFD
Computational fluid dynamics (CFD) is a new third approach in the philosophical study and
development of the whole discipline of fluid dynamics rather than theoretical and experimental
approaches. CFD is today an equal partner with pure theory and pure experiment in the analysis
of and solution of fluid flow problems. So we can say CFD is one of the branches of fluid
mechanics that uses numerical methods and algorithms to solve and analyze problems that
involve fluid flows. Computers are used to perform the millions of calculations required to
simulate the interaction of liquids and gases with surfaces defined by boundary conditions. Even
with high-speed supercomputers only approximate solutions can be achieved in many cases.
Ongoing research, however, may yield software that improves the accuracy and speed of
complex simulation scenarios such as transonic or turbulent flows. Initial validation of such
software is often performed using a wind tunnel with the final validation coming in flight test.
CFD is a Research design tool whose results are directly analogous to wind tunnel results
obtained in a laboratory-they both represent set of data for given flow configurations at different
Mach numbers, Reynolds numbers, etc.
Working Architecture:
The following steps describe the working architecture of CFD:
1. Mathematical model: The first step is to select the mathematical model which defines
the physics of fluid flow model which is to be simulated. For example we have to solve
fluid flow over a body to find lift, drag, vortex shedding, etc. We have to translate this
problem into mathematical model, formed generally by a set of partial differential
equations (Governing equations like Navier and stokes equation) and additional laws
defining the type of fluid, the eventual dependence of key parameters, such as viscosity
and heat conductivity in function of other flow quantities, such as temperature, velocity,
pressure etc.
2. Discretization: Once the mathematical model is selected, the second step which is the
major process of simulation, namely discretization process. The most fundamental
consideration in CFD is how one treats a continuous fluid in a discretized fashion on a
computer. Discretization is the process by which a closed form mathematical expression,
such as a function or a differential or integral equation involving functions, all of which
are viewed as having an infinite continuum of values throughout some domain, is
approximated by analogous (but different) expressions which prescribe values at only a
finite number of discrete points or volumes in the domain known as grid points.
Allabakshu Shaik 4
Digital Simulation Lab-1
Analyzing phase: After the discretization step, a set of algebraic relations between
neighboring mesh point values is obtained, one relation for each mesh point. This set of
equations, defining the numerical scheme, has now to be analyzed for its properties; we
have to investigate the consistency, stability and convergence which give the validity and
accuracy of a numerical scheme with the assurance that the results of the computer
simulation indeed represent a valid approximation of our reality.
3. Resolution phase: In this step solve the numerical scheme to obtain the mesh point
values of the main flow variables. The solution algorithms depend on the type of problem
we are simulating, i.e. time dependent or steady flows. This will require techniques either
to solve a set of ordinary differential equations in time, or to solve an algebraic system.
4. Analyzing Results: This is the last step in which graphic post processing is obtained for
the numerical data to understand and interpret the physical properties of the obtained
simulated results.
Briefly we can describe these five steps in three steps according to our software usages.
They are:
1. Preprocessing:
Generate the geometry of Physical flow problem like flow over a body,
flow in a nozzle with boundaries in GAMBIT.
Mesh the flow field using different techniques in GAMBIT to get the grid
points in the flow domain of the model.
Export the meshed model into FLUENT where we can solve the problem.
Set the initial conditions of the flow like steady or unsteady, implicit or
explicit, materials etc.
Select the type of model inviscid, laminar, turbulent, with heat convection
etc.
Give the input values of the flow field like velocity, pressure, temperature,
density etc.
The work of the Mathematical model, Discretization has been done in this one
step.
2. Processing:
Run the numerical scheme we had chosen.
Increase the number of iterations to get the consistency, stability and
convergence of the problem.
The work of analyzing and resolution phase has been done in this step.
Allabakshu Shaik 5
Digital Simulation Lab-1
3. Post processing:
Collect and organize the data.
Analyze the results by plotting graphs with collected data.
Visualize the CFD results by plotting contours of pressure, velocity
vectors, Path lines, streak lines.
The work of analyzing results has been done in this step.
Potential Benefits:
More cost effective and more rapid solutions than experimental fluid dynamics.
Full scale simulations (e.g. ships, airplanes, missiles etc) can be done.
Environmental effects like wind, weather can be avoided.
Hazardous like explosions, pollution, radiation can be avoided.
CFD provides high-fidelity database for diagnosing flow field.
Its applications are in various fields like Aerospace, automobile, chemical processing,
hydraulics, oil and gas, marine, biomedical, sports, power generation etc.
Allabakshu Shaik 6
Digital Simulation Lab-1
Grid Generation:
After defining governing equations for the given flow field problem then it is the time to
solve the whole system of governing equations for the flow field variables. To carry out
this work first of all, the space, where the flow is to be computed the physical space, is
to be divide in to a large number of geometrical elements called grid cells. This process is
termed grid generation (mesh). It can also be viewed as placing first grid points (also
called nodes or vertices) in the physical space and then connecting them by straight linesgrid lines. The grid normally consists in two dimensions of triangles or quadrilaterals,
and in three dimensions of tetrahedral, hexahedra, prisms, or pyramids.
The most important requirements placed on a grid generation tool are that there must not
be any holes between the grid cells but also that the grid cells do not overlap.
Additionally, the grid should be smooth, i.e., there should be no abrupt changes in the
volume of the grid cells or in the stretching ratio and the elements should be as regular as
possible. Furthermore, if the grid consists of quadrilaterals or hexahedra, there should be
no large kinks in the grid lines. Otherwise, numerical errors would increase significantly.
There exist basically two types of grids:
Structured grids (Fig. 1.1) - each grid point (vertex, node) is uniquely identified by the indices
i, j, k and the corresponding Cartesian coordinates xi,j,k, y i,j,k,, and z i,j,k,. The grid cells are
quadrilaterals in 2D and hexahedra in 3D. If the grid is body-fitted, we also speak of curvilinear
grid.
Allabakshu Shaik 7
Digital Simulation Lab-1
Unstructured grids (Fig. 1.2) - grid cells as well as grid points have no particular ordering, i.e.,
neighboring cells or grid points cannot be directly identified by their indices (e.g., cell 6 adjacent
to cell 119). In the past, the grid cells were triangles in 2D and tetrahedra in 3D. Today,
unstructured grids usually consist of a mix of quadrilaterals and triangles in 2D and of
hexahedra, tetrahedra, prisms and pyramids in 3D, in order to resolve the boundary layers
properly. Therefore, we speak in this case of hybrid or mixed grids.
Fig 1.2 Unstructured, mixed grid approach; numbers mark individual cells.
The main advantage of structured grids follows from the property that the indices i, j, k represent
a linear address space - also called the computational space, since it directly corresponds to how
the flow variables are stored in the computer memory. This property allows it to access the
neighbor of a grid point, very quickly and easily, just by adding or subtracting an integer value to
or from the corresponding index (e.g., like (i+l), (j-1), etc. - see Fig. 1.1. As one can imagine, the
evaluation of gradients, fluxes, and also the treatment of boundary conditions is greatly
simplified by this feature.
The second types of grids are the unstructured grids. They offer the largest flexibility in the
treatment of complex geometries. The main advantage of the unstructured grids is based on the
fact that triangular (2D) or tetrahedral (3D) grids can in principle be generated automatically,
independent of the complexity of the domain. In practice, it is of course still necessary to set
some parameters appropriately, in order to obtain a good quality grid. Furthermore, in order to
resolve the boundary layers accurately] it is advisable to employ in 2D rectangular and in 3D
prismatic or hexahedral elements near solid walls. Another benefit of such mixed grids is the
reduction of the number of grid cells, edges, faces and possibly also of grid points. But, one
should keep in mind that the generation of mixed grids is non-trivial for geometrically
demanding cases. However, the time required to construct an unstructured, mixed grid for a
Nimra Institute of Science and Technology
Allabakshu Shaik 8
Digital Simulation Lab-1
complex configuration is still significantly lower than the one required for a multiblock
structured grid. Since nowadays, the geometrical fidelity of the flow simulations is rapidly
increasing; the ability to generate grids fast and with minimum user interaction becomes more
and more important. This is particularly true in industrial environment. Another advantage of the
Unstructured grids are that solution dependent grid refinement and coarsening can be handled in
relatively native and seamless manner. To mention also the disadvantages of unstructured
methods, one of them is the necessity to employ sophisticated data structures inside the flow
solver. Such data structures work with indirect addressing which, depending on the computer
hardware leads to more or less reduced computational efficiency. Also the memory requirements
are in general higher as compared to the structured schemes. But despite all problems, the
capability to handle complex flow problems in short turn-around times still weights much more.
From this point, it is not surprising that for example nearly all vendors of commercial CFD
software switched over to unstructured flow solvers.
Introduction to Aerodynamics:
The study of the dynamics of air is known as aerodynamics. It includes the
intermolecular forces, the motion of molecules due to variation of flow field variables
like pressure, velocity, temperature etc.
Aerodynamics is an applied science with many practical applications in engineering. No
matter how elegant an aerodynamic theory may be, or how mathematically complex a
numerical solution may be, or how sophisticated an aerodynamic experiment may be, all
such efforts are usually aimed at one or more of the following practical objectives:
1. The prediction of forces and moments on, and heat transfer to, bodies moving
through air. For example:
Estimation of lift, drag and moments of airfoils, wings, fuselages, engine
nacelles and whole airplane.
Aerodynamic heating of flight vehicles ranging from the supersonic
transport to planetary probe entering the atmosphere of Jupiter.
2. Determination of flows moving internally through ducts. For example:
To calculate and measure the flow properties in compressors, combustion
chamber, nozzle of rockets and air breathing jet engines and to calculate
engine thrust.
To know the flow conditions in the test section of a wind tunnel.
To know how much fluid can flow through pipes under different
conditions.
A very interesting application of aerodynamics is high-energy chemical
and gas dynamic lasers.
The applications of step 1 come under external aerodynamics whereas
step 2 comes under internal aerodynamics.
Nimra Institute of Science and Technology
Allabakshu Shaik 9
Digital Simulation Lab-1
GAMBIT is the program used to generate the grid or mesh for the CFD solver.
The GAMBIT software package is designed to help analysts and designers build
and mesh models for computational fluid dynamics (CFD) and other scientific
applications. GAMBIT receives user input primarily by means of its graphical
user interface (GUI). The GAMBIT GUI makes the basic steps of building and
meshing a model simple and intuitive, yet it is versatile enough to accommodate
a wide range of modeling applications.
FLUENT is a state-of-the-art computer program for modeling fluid flow and
heat transfer in complex geometries. FLUENT is written in the C computer
language and makes full use of the exibility and powered by the language. Fluent
is the CFD solver which can handle both structured grids, i.e. rectangular grids
with clearly defined node indices, and unstructured grids. unstructured grids are
generally of triangular nature, but can also be rectangular. In 3-D problems,
unstructured grids can consist of tetrahedral (pyramid shape), rectangular boxes,
prisms, etc.
Allabakshu Shaik 10
Digital Simulation Lab-1
To create geometry of the given problem select the geometry command button
from operation tool pad.
Import the vertex data of NACA 0012 airfoil.
Create a two smooth airfoil edge for the upper surface and lower surface vertex
data by selecting Nurbs option from the Edge command of Geometry toolpad.
Split the upper surface into HI, IG, and lower surface HJ, JG by selecting split
edge option from Edge command with X=0.3 as chordlength(c) = 1.01.
Create the farfield boundary for the airfoil by creating vertices and joining them
appropriately to form edges using vertex command from geometry toolpad as per
the following table:
Label
A
B
C
D
E
F
G
X-coordinate
1.01
21.21
21.21
21.21
1.01
-11.615
1.01
Y-coordinate
12.625
12.625
0
-12.625
-12.625
0
0
Z-coordinate
0
0
0
0
0
0
0
Create the straight edges GA, AB, BC, CD, DE, EG, CG using straight edge
command and circular arc edges EF, FA with center as G using arc edge
command from geometry tool pad. Thus the farfield boundary is created for the
airfoil.
Create the face ABCGA by selecting GA, AB, BC, CG edges in create face from
wireframe command. Similarly create faces GCDEG, GEFAG, airfoil (HIGJH).
Subtract the airfoil face from GEAFG face using subtract real faces command.
Allabakshu Shaik 11
Digital Simulation Lab-1
Thus the geometry of flow over 0012 airfoil has been completed.
2. Mesh geometry in Gambit:
To create the mesh for the geometry select mesh command button from the
operation tool pad.
Instead of directly meshing the faces of geometry, first we mesh the edges by
giving inputs like type of mesh, ratio or length of nodes, direction, interval count
or size for each edge of the geometry in Mesh Edges command button as follows:
Edges GA and BC
Type
: Successive ratio
Ratio
: 1.15
Direction
: from G to A and C to B
Interval count : 45
Edges EG and CD
Type
: Successive ratio
Ratio
: 1.15
Direction
: from G to E and C to D
Interval count : 45
Edges AB, CG and DE
Type
: First Length
Length
: 0.0202
Direction
: from A to B, G to C and E to D
Interval count : 60
Edges HI and HJ
Type
: Last Length
Length
: 0.0202
Direction
: from H to I and H to J
Interval count : 40
Edges IG and JG
Type
: Successive ratio
Ratio
:1
Direction
: from I to G and J to G
Interval size : 0.0202
To mesh the edges AF and EF we should find the number of nodes on upper
surface and lower surface of the airfoil which should be equal to the nodes
obtained by meshing edges AF and EF respectively.
So select Edge command-summarize edge mesh. Select edge IJ and then elements
under component and click apply then number of divisions will appear. So, the
interval count for edge AF is NHI+NIG = 40+36 = 76. Similarly for the edge EF
also interval count is NHJ+NJG = 40+36 = 76.
Allabakshu Shaik 12
Digital Simulation Lab-1
Edges AF and EF
Type
: First Length
Length
: 0.0202
Direction
: from A to F and E to F
Interval count : 76
Go to Mesh Faces select the face GABCG and make sure that type of mesh is
map, elements are quad and then apply then we will get a meshed face. Similarly
for face GCDEG and subtracted face of GEFAG with airfoil.
Thus the Meshed geometry for the given flow problem is obtained.
Allabakshu Shaik 13
Digital Simulation Lab-1
Allabakshu Shaik 14
Digital Simulation Lab-1
6. Analyze results:
Plot XY plot.
Change the Y-axis function to pressure followed by pressure coefficient.
Select airfoil under surfaces.
Click on Plot.
Distribution of pressure coefficient on airfoil is displayed.
Display Contours.
Select pressure, static pressure under contours and then display.
Similarly obtain velocity contours and etc.
Allabakshu Shaik 15
Digital Simulation Lab-1
This plot shows pressure coefficient over NACA 0012 airfoil at =50
This plot shows pressure contours over flow field when NACA 0012 airfoil at =50
Nimra Institute of Science and Technology
Allabakshu Shaik 16
Digital Simulation Lab-1
This plot shows pressure contours over flow field when NACA 0012 airfoil at =80
This plot shows velocity contours over flow field when NACA 0012 airfoil at =80
Allabakshu Shaik 17
Digital Simulation Lab-1
RESULTS
Angle of attack
Coefficient of Drag
0.592
0.919
1.0583
0.0022
0.0406
0.1107
5
80
120
Allabakshu Shaik 18
Digital Simulation Lab-1
attacks.
Create the geometry of aerofoil which is the cross sectional shape of wing.
Create the boundary for the aerofoil according to the following points.
Vertex
XYZcoordinate coordinate coordinate
A
4
4
0
B
4
-4
0
C
-3
-3
0
D
-3
3
0
2. Mesh geometry:
Mesh the edges of the original faces of the airfoil and boundary.
First create the mesh for edges as follows:
Edges
Upper surface
Lower surface
AB
BC
CD
DA
Successive ratio
1
1
1
1
1
1
Interval count
60
60
300
300
300
300
Allabakshu Shaik 19
Digital Simulation Lab-1
Name
Face 5
Inlet
Face 6
Outlet
Face 2 & 9
Sides
Airfoil
Allabakshu Shaik 20
Digital Simulation Lab-1
Allabakshu Shaik 21
Digital Simulation Lab-1
6. Analyze results:
Plot XY plot.
Change the Y-axis function to pressure followed by pressure coefficient.
Select surfaces.
Click on Plot.
Display contours
Allabakshu Shaik 22
Digital Simulation Lab-1
Allabakshu Shaik 23
Digital Simulation Lab-1
Allabakshu Shaik 24
Digital Simulation Lab-1
Allabakshu Shaik 25
Digital Simulation Lab-1
Conclusion:
1. Angle of attack =0
Cl =
Iterations
Angle of
attack
00
345
50
474
150
849
Co-efficient of
lift
0.00906
0.35337
1.4356
Co-efficient of
drag
0.0067
0.05744
0.0151
Co-effiecient of
moment
0.00412
0.08701
0.3647
Allabakshu Shaik 26
Digital Simulation Lab-1
Import the vertex data of Nozzle cross sectional area variation along axis.
Draw the axis line with vertices (-0.5, 0) and (0.5, 0) and make axis symmetric
problem.
Create edges and face of nozzle using geometry command button.
8. Mesh geometry:
Let us start with edge mesh, consider left and right (inlet and outlet) edges mesh
with no grading option and interval count is 20 using Mesh command button.
Mesh the top and bottom edges (wall and center line) with interval count 50.
Finally Face mesh, select all edges click apply.
Allabakshu Shaik 27
Digital Simulation Lab-1
Type
Pressure inlet
Pressure outlet
Wall
Axis
Name
Inlet
Outlet
Wall
Centerline
Clicks apply.
Save the file and export 2d mesh file.
Allabakshu Shaik 28
Digital Simulation Lab-1
Define-Boundary conditions
Zone Inlet Pressure inlet
Guage total pressure = 101325pa
Supersonic/Intial gauge pressure 99300pa
Total temperature = 300K
Under turbulence method select intensity and
hydraulic diameter set turbulence intensity = 1
Hydraulic diameter = 0.6677.
o Zone - farfield3 - pressure outlet
Gauge pressure (pa), this value changes according
to conditions in required in divergent section of
nozzle as follows:
(a) For Normal shock = 49650pa.
(b) For supersonic flow = 24825pa
(c) For subsonic flow = 198600pa
Under turbulence method select intensity and
hydraulic diameter set turbulence intensity = 1
Hydraulic diameter = 0.6677.
o Zone - wall - wall.
Now the flow problem is ready to solve.
Allabakshu Shaik 29
Digital Simulation Lab-1
12.Analyze results:
Plot XY plot.
Change the Y-axis function to pressure followed by pressure coefficient.
Select surfaces.
Click on Plot.
Display velocity - Machnumber contours in the nozzle
Allabakshu Shaik 30
Digital Simulation Lab-1
Fig (a)
SONIC THROAT AND SUPERSONIC VELOCITY IN DIVERGENT SECTION
Allabakshu Shaik 31
Digital Simulation Lab-1
Fig (b)
SONIC THROAT SUBSONIC VELOCITY IN THE DIVERGENT SECTION
Nimra Institute of Science and Technology
Allabakshu Shaik 32
Digital Simulation Lab-1
Fig (c)
Allabakshu Shaik 33
Digital Simulation Lab-1
RESULTS
1. From fig (a) it can be seen that normal shock is going to form at X = 0.3 along the axis of
nozzle.
Static pressure at inlet = 96376.414pa
Static pressure at outlet = 49117.016pa
2. From fig (b) the flow is supersonic and isentropic in the divergent section.
Static pressure at inlet = 95918.297pa
Static pressure at outlet = 5584.5322pa
3. From fig (c) the flow is subsonic and isentropic in the divergent section.
Static pressure at inlet = 97393.719pa
Static pressure at outlet = 188993.14pa
Allabakshu Shaik 34
Digital Simulation Lab-1
Allabakshu Shaik 35
Digital Simulation Lab-1
Lets start by entering a few really basic commands. If you want to find the value of a numerical
expression, simply type it in. Lets say we want to know the value of 433.12 multiplied by 15.7. We type
433.12 * 15.7 at the MATLAB prompt and hit the enter key. The result looks like this:
>> 433.12*15.7
ans =
6.8000e+003
Allabakshu Shaik 36
Digital Simulation Lab-1
MATLAB comes with many basic or familiar mathematical quantities and functions built in.
How to use in an example.
The volume of a sphere is given by
V 4/33
Of course MATLAB comes with predefined. To use it, we just type pi. So after
defining a variable to hold the radius, we can find the volume by typing
>> r = 2;
>> V = (4/3) *pi*r^3
V =
33.5103
>> exp(1)
ans =
2.7183
To find the square root of a number, we type sqrt. For example
>> x = sqrt(9)
x =
3
>> y = sqrt(11)
y =
3.3166
Allabakshu Shaik 37
Digital Simulation Lab-1
Allabakshu Shaik 38
Digital Simulation Lab-1
Allabakshu Shaik 39
Digital Simulation Lab-1
Save the file by clicking the Save icon in the file editor or by selecting Save As from the
File pull-down menu.
Save the file as example1.m in your MATLAB directory.
Now return to the MATLAB desktop command window. Type in example1. If you did
everything right, then you will see the following output
>> example1
y=
2.7183 7.3891 20.0855 54.5982
We can also use M-files to create and store data. For an example, lets create a set of
temperatures that we will store in a file. We do this by creating a list of temperatures in the file
editor
temps = [32,50,65,70,85]
Now we save this as a file that well call TemperatureData.m. We store this file in the
MATLAB directory. To access it in the command window, we just type the name of the . le.
MATLAB responds by spitting out the list of numbers:
>> TemperatureData
temps =
32 50 65 70 85
Now we can use the data by referring to the array name used in the file. Lets create
another set of numbers called Celsius that converts these familiar temps into the European style
Celsius temperatures we are so familiar with. This can be done with the following command
>> CelsiusTemps = (5/9) * (temps - 32)
CelsiusTemps =
0 10.0000 18.3333 21.1111 29.4444
VECTORS:
A vector is a one-dimensional array of numbers. MATLAB allows you to create column vectors
or row vectors. A column vector can be created in MATLAB by enclosing a set of semicolon
delimited numbers in square brackets. Vectors can have any number of elements. For example,
to create a column vector with three elements we write:
>> a = [2; 1; 4]
a=
2
1
4
Nimra Institute of Science and Technology
Allabakshu Shaik 40
Digital Simulation Lab-1
To create a row vector, we enclose a set of numbers in square brackets but this time use a space
or comma to delimit the numbers. For example:
>> v = [2 0 4]
v=
2
0
4
Or using commas:
>> w = [1,1,9]
w=
In MATLAB, we represent the transpose operation with a single quote or tickmark ().
Taking the transpose of a column vector produces a row vector:
Now lets take the transpose of a row vector to produce a column vector:
>> Q = [2 1 3]
Q=
2
1
3
>> R = Q'
R=
2
1
3
It is also possible to add or subtract two vectors to produce another. In order to perform
this operation the vectors must both be of the same type and the same length, so we can add two
column vectors together to produce a new column vector or we can add two row vectors to
produce a new row vector, for example. This can be done referencing the variables only, it is not
necessary for the user to list the components. For example, lets add two column vectors
together:
>> A = [1; 4; 5];
>> B = [2; 3; 3];
>> C = A + B
C=
3
7
8
Now lets subtract one row vector from another:
>> W = [3,0,3];
>> X = [2,1,1];
>> Y = W X
Y=
1
1
2
VECTOR DOT AND CROSS PRODUCT:
Nimra Institute of Science and Technology
Allabakshu Shaik 41
Digital Simulation Lab-1
In MATLAB, the dot product of two vectors a, b can be calculated using the dot(a,b)
command. The dot product between two vectors is a scalar, i.e. its just a number. Lets compute
a simple example using MATLAB:
>> a = [1;4;7]; b = [2;1;5];
>> c = dot(a,b)
c=
33
The dot product can be used to calculate the magnitude of a vector. All that needs to be done is
to pass the same vector to both arguments. Consider the vector in the last section:
>> J = [0; 3; 4];
Calling dot we obtain:
>> dot(J,J)
ans =
25
Another important operation involving vectors is the cross product. To compute the cross
product, the vectors must be three dimensional. For example:
>> A = [1 2 3]; B = [2 3 4];
>> C = cross(A,B)
C=
1
2
1
MATRICES:
A matrix is a two-dimensional array of numbers. To create a matrix in MATLAB, we
enter each row as a sequence of comma or space delimited numbers, and then use semicolons to
mark the end of each row. For example, consider:
Multiplication:
Nimra Institute of Science and Technology
Allabakshu Shaik 42
Digital Simulation Lab-1
These are both 2 2 matrices, so matrix multiplication is permissible. First, lets do array
multiplication so we can see the difference:
>> A = [2 1; 1 2]; B = [3 4; 5 6];
>> A.*B
ans =
6
4
5
12
Now we leave out the . character and execute matrix multiplication, which produces quite a
different answer:
>> A*B
ans =
11
14
13
16
The identity matrix is a square matrix that has ones along the diagonal and zeros elsewhere. To
create an
n x n identity matrix, type the following MATLAB command: eye(n)
Lets create a 4 4 identity matrix:
>> eye(4)
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
DETERMINANTS:
The determinant of a square matrix is a number. For a 2 x 2 matrix, the determinant is given by:
To calculate the determinant of a matrix A in MATLAB, simply write det(A). Here is the
determinant of a 2 x 2 matrix:
>> A = [1 3; 4 5];
Nimra Institute of Science and Technology
Allabakshu Shaik 43
Digital Simulation Lab-1
>> det(A)
ans =
7
In this example, we find the determinant of a 4 x 4 matrix:
>> B = [3 1 2 4; 0 2 1 8; 9 17 11 3; 1 2 3 3];
>> det(B)
ans =
533
INVERSE OF A MATRIX AND SOLVIND LINEAR EQUATIONS:
The inverse of a matrix A is denoted by A-1 such that the following relationship is satisfied:
AA-1 = A-1A = 1
Consider the following matrix equation:
Ax = b
If the inverse of A exists, then the solution can be readily written as:
x = A-1b
In practice, this is much harder than it looks because computing the inverse of a matrix can be a
tedious pain. Luckily MATLAB makes things easy for us by doing all of the tedious work we
want to avoid. The inverse of a matrix A can be calculated in MATLAB by writing:
inv(A)
The inverse of a matrix does not always exist. In fact, we can use the determinant to determine
whether or not the inverse exists. If det(A) = 0, then the inverse does not exist and we say the
matrix is singular.
Lets get started by calculating a few inverses just to see how easy this is to do in
MATLAB. Starting with a simple 2 x 2 matrix:
First lets check the determinant of A to ensure that the inverse exists:
>> det(A)
ans =
6
Since the inverse exists, we can generate the solution readily in MATLAB:
>> x = inv(A)*b
x=
1.0000
4.0000
Allabakshu Shaik 44
Digital Simulation Lab-1
Now we can plot the function. This is done by entering the following command:
>> plot(x, y)
After typing the plot command, hit the enter key. After a moment MATLAB will open a new
window on the screen with the caption Figure 1. The plot is found in this window.
Fplot:
Nimra Institute of Science and Technology
Allabakshu Shaik 45
Digital Simulation Lab-1
The function fplot gets around our choice of interval used to generate the plot, and instead
decides the number of plotting points to use for us. Generally, fplot will allow you to generate the most
accurate plots possible, but it also helps us get around errors like these. The formal call to fplot goes like
fplot (function string, [xstart, xend]). The argument function string tells fplot the function you want to
plot while xstart and xend define the range over which to display the plot. This is pretty straightforward,
lets see how it works out in the current example. We can do it all in one go by typing the following
command and hitting the enter key:
>> fplot('exp(-2*t)*sin(t)',[0, 4]);
MATLAB quickly produces the plot shown in Figure. If we want to add labels and a title to the plot, we
can follow the same procedure used with plot(x,y). Lets try it again this time adding our title Damped
Spring Forcing and labeling our axes:
>> fplot('exp(2*t)*sin(t)',[0,4]), xlabel('t'), ylabel('f(t)'),
title('Damped Spring Forcing')
Allabakshu Shaik 46
Digital Simulation Lab-1
To plot multiple functions, we simply call the plot(x, y) command with multiple pairs x, y defining the
independent and dependent variables used in the plot in pairs. This is followed by a character string
enclosed in single quotes to tell us what kind of line to use to generate the second curve. In this case we
have:
>> plot(t,f,t,g,'--')
This tells MATLAB to generate plots of f(t) and g(t) with the latter function displayed as a dashed line.
Note that while we cant show it in the book, MATLAB displays each curve with a unique color.
The color of each curve can be set automatically by MATLAB or we can manually select which color we
want. This is done by enclosing the appropriate letter assigned to each color used by MATLAB in single
quotes immediately after the function to be plotted is specified.
Color
White
Black
Red
Cyan
Green
Magneta
Yellow
Specifier
w
k
r
c
g
m
y
The legend command is simple to use. Just add it to the line used for the plot(x, y) command and add a
text string enclosed in single quotes for each curve you want to label. In our case we have:
>> legend('sinh(x)','cosh(x)')
Allabakshu Shaik 47
Digital Simulation Lab-1
Allabakshu Shaik 48
Digital Simulation Lab-1
1. BASIC MATHEMATICS
1.
Solve
>> 5*(11/14)
ans =
3.9286
2. Solve
>> 5*(8/3)+3^7
ans =
2.2003e+003
3. Solve
>> 9^1.25
ans =
15.5885
4. True or False. If y has not been assigned a value, MATLAB will allow you to define the
equation x = y ^2 to store in memory for later use.
>> x=y^2;
??? Undefined function or variable 'y'.
Hence statement is False.
5. If the volume of a cylinder of height h and radius r is given by V r2h,
use MATLAB to . nd the volume enclosed by a cylinder that is 12 cm high
with a diameter of 4 cm.
>> r=2;
>> h=12;
>> V=h*pi*r^2
Nimra Institute of Science and Technology
Allabakshu Shaik 49
Digital Simulation Lab-1
V =150.7964
Save the file and run the file then results are displayed in command window as follows:
ans =
0.8660
ans =
0.7071
Nimra Institute of Science and Technology
Allabakshu Shaik 50
Digital Simulation Lab-1
ans =
1
Allabakshu Shaik 51
Digital Simulation Lab-1
7i
22i).
Allabakshu Shaik 52
Digital Simulation Lab-1
-40.0000 + 6.0000i
>> mag = sqrt(a)
mag =
0.4730 + 6.3422i
>> a = [1;2;3]
a=
1
2
3
4. Given A = [1; 2; 3]; B = [4; 5; 6]; find the array product of the two vectors.
>> A=[1;2;3],B=[4;5;6]
A=
1
2
3
B=
4
5
6
Allabakshu Shaik 53
Digital Simulation Lab-1
>> A.*B
ans =
4
10
18
5. What command would create a 5x5 matrix with ones on the diagonal and zeros
everywhere else?
>> eye(5)
ans =
1
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
1
7
5
2
11
-1
-8
1
6
2
2
4
2
B=
2
-1
2
>> A.*B
ans =
16
22
Allabakshu Shaik 54
Digital Simulation Lab-1
-6
0
30 -4
4 -16
Suppose that A
Use it to create B
Defining matrix %
Allabakshu Shaik 55
Digital Simulation Lab-1
A=
1
-4
9
2 3
1 2
0 -8
B=
12
13
-1
>> c=[A B]
c=
1 2 3 12
-4 1 2 13
9 0 -8 -1
>> rank (A)
ans =
3
>> rank (c)
ans =
3
>> X=A\B
X=
-1.7619
9.6667
-1.8571
>> det (A)
ans =
-63
9. Does a solution to the following system exist? What is it?
x 2y 3z = 1
x 4y 3z = 2
2x 8y z =
>> A = [ 1 -2 3 ; 1 4 3 ; 2 8 1] , B = [ 1 ; 2 ; 3 ]
A=
1
1
-2
4
3
3
Allabakshu Shaik 56
Digital Simulation Lab-1
B=
1
2
3
>> det(A)
ans =
-30
7 -9
-1 4
1 -7
B=
12
16
16
>> [L, U] = lu(A)
L=
0.5000
1.0000
0.5000
1.0000
0
0.2000
0
0
1.0000
Allabakshu Shaik 57
Digital Simulation Lab-1
U=
2.0000
0
0
>> X = U\(L\B)
-1.0000
4.0000
7.5000 -11.0000
0
-6.8000
X=
9.6078
-1.0196
-1.0588
Allabakshu Shaik 58
Digital Simulation Lab-1
2. Show the same plot, with sin(x) added to the graph as a second curve.
>> x = [0:0.1:1];
>> plot ( x, tan(x) )
>> hold on
>> plot ( x, sin(x) )
Allabakshu Shaik 59
Digital Simulation Lab-1
0.0584
0.2584
Columns 19 through 27
0.4584
0.6584
0.8584
1.0584
1.2584
2.8584
3.0584
1.4584
1.6584
Columns 28 through 32
2.2584
2.4584
2.6584
1.8584
2.0584
Allabakshu Shaik 60
Digital Simulation Lab-1
0.0317
0.0952
0.1587
0.2221
Columns 55 through 63
0.2856
0.3491
0.4125
0.4760
0.5395
0.6029
0.6664
0.7299
0.7933
1.0472
1.1107
1.1741
1.2376
1.3011
1.3645
1.6184
1.6819
1.7453
1.8088
1.8723
1.9357
2.1896
2.2531
2.3165
2.3800
2.4435
2.5069
2.7608
2.8243
2.8877
2.9512
3.0147
3.0781
Columns 64 through 72
0.8568
0.9203
0.9837
Columns 73 through 81
1.4280
1.4915
1.5549
Columns 82 through 90
1.9992
2.0627
2.1261
Columns 91 through 99
2.5704
2.6339
2.6973
Column 100
Nimra Institute of Science and Technology
Allabakshu Shaik 61
Digital Simulation Lab-1
3.1416
>> linspace(-pi,pi,50) % 50 uniformly spaced points %
ans =
Columns 1 through 9
-3.1416 -3.0134 -2.8851 -2.7569 -2.6287 -2.5005 -2.3722 -2.2440 -2.1158
Columns 10 through 18
-1.9875 -1.8593 -1.7311 -1.6029 -1.4746 -1.3464 -1.2182 -1.0899 -0.9617
Columns 19 through 27
-0.8335 -0.7053 -0.5770 -0.4488 -0.3206 -0.1923 -0.0641
0.0641
0.1923
Columns 28 through 36
0.3206
0.4488
0.5770
0.7053
0.8335
0.9617
1.0899
1.2182
1.3464
1.8593
1.9875
2.1158
2.2440
2.3722
2.5005
3.0134
3.1416
Columns 37 through 45
1.4746
1.6029
1.7311
Columns 46 through 50
2.6287
2.7569
2.8851
Allabakshu Shaik 62
Digital Simulation Lab-1
>> [x,y]=meshgrid(-5:0.2:5);
>> z=cos(x).*sin(y);
>> mesh(x,y,z),xlabel('x'),ylabel('y'),zlabel('z');
Allabakshu Shaik 63
Digital Simulation Lab-1
5. Plot the curve x = et cos t, y = et sin t, z = t using the plot3 function. Dont label the
axes, but turn on the grid.
>> t=meshgrid(0:0.1:1);
>> x=exp(-t)*cos(t);
>> y=exp(-t)*sin(t);
>> z=t;
>> mesh(x,y,z),xlabel('x'),ylabel('y'),zlabel('z');
Allabakshu Shaik 64
Digital Simulation Lab-1
Allabakshu Shaik 65
Digital Simulation Lab-1
-5
+5
>> eq = '7*sqrt(2)-5*sqrt(60)+5*sqrt(8)'
eq =
7*sqrt(2)-5*sqrt(60)+5*sqrt(8)
>> 7*sqrt(2)-5*sqrt(60)+5*sqrt(8)
ans =
-14.6882
+ 2x = 7.
>> eq = '3*(x^2)+2*x=7'
eq =
3*(x^2)+2*x=7
>> s = solve (eq)
s=
-1/3+1/3*22^(1/2)
-1/3-1/3*22^(1/2)
>> x = double(s(1))
x=
1.2301
>> y = double(s(2))
y=
-1.8968
Allabakshu Shaik 66
Digital Simulation Lab-1
x .
>> eq = 'x^2+sqrt(5)*x-pi=0'
eq =
x^2+sqrt(5)*x-pi=0
>> s = solve(eq)
s=
-1/2*5^(1/2)+1/2*(5+4*pi)^(1/2)
-1/2*5^(1/2)-1/2*(5+4*pi)^(1/2)
>> x=double(s)
x=
0.9776
-3.2136
and symbolically plot the function for 2 < x < 4, 0 < y<1.
>> eq = 'sqrt(2*x-4)-1'
eq =
sqrt(2*x-4)-1
>> s = solve(eq)
s=
5/2
>> ezplot(eq)
Allabakshu Shaik 67
Digital Simulation Lab-1
>> eq = '2*t^3-t^2+4*t-6'
eq =
2*t^3-t^2+4*t-6
>> ezplot(eq)
>> s = solve (eq)
s=
1/6*(289+6*2658^(1/2))^(1/3)-23/6/(289+6*2658^(1/2))^(1/3)+1/6
-1/12*(289+6*2658^(1/2))^(1/3)+23/12/(289+6*2658^(1/2))^(1/3)+1/6+1/2*i*3^(1/2)*
(1/6*(289+6*2658^(1/2))^(1/3)+23/6/(289+6*2658^(1/2))^(1/3))
-1/12*(289+6*2658^(1/2))^(1/3)+23/12/(289+6*2658^(1/2))^(1/3)+1/61/2*i*3^(1/2)*(1/6*(289+6*2658^(1/2))^(1/3)+23/6/(289+6*2658^(1/2))^(1/3))
Nimra Institute of Science and Technology
Allabakshu Shaik 68
Digital Simulation Lab-1
>> x= double(s)
x=
1.1162
-0.3081 + 1.6102i
-0.3081 - 1.6102i
Allabakshu Shaik 69
Digital Simulation Lab-1
>> z = s.z
z=
2
Allabakshu Shaik 70
Digital Simulation Lab-1
Allabakshu Shaik 71
Digital Simulation Lab-1
2. Solve:
= 2.3y,
y(0) = 0
Allabakshu Shaik 72
Digital Simulation Lab-1
>> plot(t,y),xlabel('t'),ylabel('y1')
Allabakshu Shaik 73
Digital Simulation Lab-1