Basic Simulation Lab File (Es-204) : Ravi Kumar A45615820008 B.Tech Ce 4 SEM
Basic Simulation Lab File (Es-204) : Ravi Kumar A45615820008 B.Tech Ce 4 SEM
Basic Simulation Lab File (Es-204) : Ravi Kumar A45615820008 B.Tech Ce 4 SEM
RAVI KUMAR
A45615820008
B.TECH CE
4THSEM
TABLE OF CONTENTS
DATE OF DATE OF
S.NO. TITLE OF THE EXPERIMENTS
EXPERIMENT SUBMISSION
THEORY:
MATLAB is an interactive system whose basic data element is an array that does not
require dimensioning. This allows you to solve many technical computing problems,
especially those with matrix and vector formulations, in a fraction of the time it would
take to write a SUGGESTED PROGRAM: in a scalar non interactive language such as C
or Fortran. The name MATLAB stands for matrix laboratory.
Matrix Addition and Subtraction is performed by merely adding or subtracting the matrix
elements by their corresponding elements in the other matrix.
The inverse of a matrix does not always exist. If the determinant of the matrix is zero,
then the inverse does not exist and the matrix is singular.
Transpose operation switches the rows and columns in a matrix. It is represented by a single
quote(').
Rank function provides an estimate of the number of linearly independent rows or columns
of a null matrix.k = rank(A) returns the number of singular values of A that are larger than the
default tolerance, max(size(A))*eps(norm(A)).
k = rank(A,tol) returns the number of singular values of A that are larger than tol.
MATLAB PROGRAM:-
COMMAND WINDOW RESULT:-
FIGURES
CONCLUSION
The given experiment has been performed successfully.
EXPERIMENT:2
THEORY:
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. MATLAB is designed to operate primarily on whole matrices and arrays.
Therefore, operators in MATLAB work both on scalar and non-scalar data. MATLAB allows
the following types of elementary operations:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operations
5. Set Operations
6. Arithmetic Operators
Matrix arithmetic operations are same as defined in linear algebra. Array operations are
executed element by element, both on one-dimensional and multidimensional array.
The matrix operators and array operators are differentiated by the period (.) symbol.
However, as the addition and subtraction operation is same for matrices and arrays, the
operator is same for both cases. The following table gives brief description of the operators:
Operator Description
Addition or unary plus. A+B adds A and B. A and B must have the same
+
size, unless one is a scalar. A scalar can be added to a matrix of any size.
Subtraction or unary minus. A-B subtracts B from A. A and B must have the
- same size, unless one is a scalar. A scalar can be subtracted from a matrix of
any size.
Matrix multiplication. C = A*B is the linear algebraic product of the
matrices A and B. More precisely,
* For nonscalar A and B, the number of columns of A must equal the number
of rows of B. A scalar can multiply a matrix of any size.
Relational Operators
Relational operators can also work on both scalar and non-scalar data. Relational operators
for arrays perform element-by-element comparisons between two arrays and return a logical
array of the same size, with elements set to logical 1 (true) where the relation is true and
elements set to logical 0 (false) where it is not.
Operator Description
< Less than
<= Less than or equal to
Logical Operators
Element-wise logical operators operate element-by-element on logical arrays. The symbols &,
|, and ~ are the logical array operators AND, OR, and NOT.
Short-circuit logical operators allow short-circuiting on logical operations. The symbols &&
and || are the logical short-circuit operators AND and OR.
Bitwise Operations
Bitwise operator works on bits and performs bit-by-bit operation. The truth tables for &, |, and
^ are as follows:
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
~A = 1100 0011
MATLAB provides various functions for bit-wise operations like 'bitwise and', 'bitwise or'
and 'bitwise not' operations, shift operation, etc.
Function Purpose
bitand(a, b) Bit-wise AND of integers a and b
bitcmp(a) Bit-wise complement of a
bitget(a,pos) Get bit at specified position pos, in the integer array a
bitor(a, b) Bit-wise OR of integers a and b
bitset(a, pos) Set bit at specific location pos of a
Returns a shifted to the left by k bits, equivalent to multiplying by 2k.
Negative values of k correspond to shifting bits right or dividing by
bitshift(a, k)
2|k| and rounding to the nearest integer towards negative infinite. Any
overflow bits are truncated.
bitxor(a, b) Bit-wise XOR of integers a and b
swapbytes Swap byte ordering
Set Operations
MATLAB provides various functions for set operations, like union, intersection and testing
for set membership, etc.
Function Description
Set intersection of two arrays; returns the values common to both A
intersect(A,B)
and B. The values returned are in sorted order.
Treats each row of A and each row of B as single entities and returns
intersect(A,B,'rows') the rows common to both A and B. The rows of the returned matrix
are in sorted order.
Returns an array the same size as A, containing 1 (true) where the
ismember(A,B)
elements of A are found in B. Elsewhere, it returns 0 (false).
Treats each row of A and each row of B as single entities and returns a
ismember(A,B,'rows') vector containing 1 (true) where the rows of matrix A are also rows of
B. Elsewhere, it returns 0 (false).
Returns logical 1 (true) if the elements of A are in sorted order and
logical 0 (false) otherwise. Input A can be a vector or an N-by-1 or 1-
issorted(A)
by-N cell array of strings. A is considered to be sorted if A and the
output of sort(A) are equal.
Returns logical 1 (true) if the rows of two-dimensional matrix A are in
issorted(A, 'rows') sorted order, and logical 0 (false) otherwise. Matrix A is considered to
be sorted if A and the output of sortrows(A) are equal.
Set difference of two arrays; returns the values in A that are not in B.
setdiff(A,B)
The values in the returned array are in sorted order.
Treats each row of A and each row of B as single entities and returns
the rows from A that are not in B. The rows of the returned matrix are
setdiff(A,B,'rows') in sorted order.
The 'rows' option does not support cell arrays.
MATLAB PROGRAM:-
CONCLUSION:-
The given experiment has been performed successfully.
EXPERIMENT:3
THEORY:
VECTORS:
Matrices with one dimension equal to one and the other greater than one are called vectors.
Here is an example of a numeric vector:
A = [5.73 2-4i 9/7 25e3 .046 sqrt(32) 8j];
size(A) % Check value of row and column dimensions
ans =
1 7
We can construct a vector out of other vectors, as long as the critical dimensions agree. All
components of a row vector must be scalars or other row vectors. Similarly, all
components of a column vector must be scalars or other column vectors: A = [29 43 77 9
21];
B = [0 46 11];
C = [A 5 ones(1,3) B]
C=
29 43 77 9 21 5 1 1 1 0 46 11
RANDOM:
rand:
The rand function generates arrays of random numbers whose elements are uniformly
distributed in the interval (0,1).
Y = rand(n) returns an n-by-n matrix of random entries.An error message appears if n is not
a scalar.
Y = rand(size(A)) returns an array of random entries that is the same size as A. rand, by
itself, returns a scalar whose value changes each time it's referenced.
s = rand('state') returns a 35-element vector containing the current state of the uniform
generator.
randn:
The randn function generates arrays of random numbers whose elements are normally
distributed with mean 0, variance (sigma^2=1) , and standard deviation (sigma=1) .
Y = randn(n) returns an n-by-n matrix of random entries. An error message appears if n is not
a scalar.
s = randn('state') returns a 2-element vector containing the current state of the normal
generator. To change the state of the generator
PROCEDURE:
EXPERIMENT:4
AIM: Evaluating a given expression and rounding it to the nearest integer value using
Round, Floor, Ceil and Fix functions; Also, generating and Plots of (A) Trigonometric
Functions - sin(t),cos(t), tan(t), sec(t), cosec(t) and cot(t) for a given duration, ‘t’. (B)
Logarithmic and other Functions – log(A), log10(A), Square root of A, Real nth root of A.
THEORY:
Round
Round to nearest
integer Syntax: Y =
round(X)
Description: Y = round(X) rounds the elements of X to the nearest integers. For complex X,
the imaginary and real parts are rounded independently.
Floor
Round towards minus infinity
Syntax B = floor(A)
Description B = floor(A) rounds the elements of A to the nearest integers less than or equal to
A. For complex A, the imaginary and real parts are rounded independently.
Ceil
Round toward infinity
Syntax: B = ceil(A)
Description: B = ceil(A) rounds the elements of A to the nearest integers greater than or equal
to A. For complex A, the imaginary and real parts are rounded independently.
Fix
Round towards zero
Syntax: B = fix(A)
Description: B = fix(A) rounds the elements of A toward zero, resulting in an array of
integers. For complex A, the imaginary and real parts are rounded independently.
Trigonometric Functions
The trigonometric functions are used along with their names and have the angle value as the
parameters in them. A range for the value of the parameter is defined to attain their graphical
representations.
Syntax: A = ‘trigonometric function
name’(Value) Ex. sin(30), cos(115), tan(-45)
PROCEDURE:
EXPERIMENT:5
AIM: Creating a vector X with elements, Xn = (-1)n+1/(2n-1) and Adding up 100 elements
of the vector, X; And, plotting the functions, x, x3, ex, exp(x2) over the interval 0 < x < 4 (by
choosing appropriate mesh values for x to obtain smooth curves), on A Rectangular Plot
THEORY:
MATLAB PROGRAM:-
a=x.^3;
>> n = 1:100; plot(a(1,1:4))
x = ( (-1).^(n+1) ) ./ (2*n - 1);
Exp(x)
y = sum(x)
b=exp(x)
x plot(b(1,1:4))
plot(x(1,1:4))
Exp(n2)
c=exp(x.^2);
plot(c(1,1:4)
)
y=
0.7829
FIGURES
CONCLUSION:-
The given experiment has been performed successfully.
EXPERIMENT:6
AIM: Generating a Sinusoidal Signal of a given frequency (say, 100Hz) and Plotting
with Graphical Enhancements - Titling, Labeling, Adding Text, Adding Legends, Adding
New Plots to Existing Plot, Printing Text in Greek Letters, Plotting as Multiple and
Subplot.
THEORY:
The sin function operates element-wise on arrays. The function's domains and ranges
include complex values. All angles are in radians.
Y = sin(X) returns the circular sine of the elements of X.
MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to
adjust the axes to spruce up the graph.
1. The xlabel and ylabel commands generate labels along x-axis and y-axis.
2. The title command allows you to put a title on the graph.
3. The grid on command allows you to put the grid lines on the graph.
4. The axis equal command allows generating the plot with the same scale factors and
the spaces on both
5. axes.
6. The axis square command generates a square
plot. Setting Colors on Graph
MATLAB provides eight basic color options for drawing graphs. The following table
shows the colors and their codes:
Color Code
White w
Black k
Blue b
Red r
Cyan c
Green g
Magenta m
Yellow y
The axis command allows you to set the axis scales. You can provide minimum and
maximum values for x and y axes using the axis command in the following way:
axis ( [xmin xmax ymin ymax] )
Generating Sub-Plots
When you create an array of plots in the same figure, each of these plots is called a subplot.
Thesubplot command is for creating subplots.
Syntax for the command is:
subplot(m, n, p)
where, m and n are the number of rows and columns of the plot array and p specifies where to
put a particular plot.
MATLAB PROGRAM:-
%Generating a Sinusoidal Signal of a given frequency with Titling, Labeling, Adding Text,
Adding Legends, Printing Text in Greek Letters, Plotting as Multiple and Subplot. Time scale
the generated signal for different values. E.g. 2X, 4X, 0.25X, 0.0625X. %
t=-0.25:0.0001:0.25;
f1=3;
y1=sin(2*pi*f1*t);
y2=sin(2*pi*f1*2*t);
y3=sin(2*pi*f1*4*t);
y4=sin(2*pi*f1*0.25*t);
y5=sin(2*pi*f1*0.625*t);
plot(t,y1,'k',t,y2,'g',t,y3,'b',t,y4,'m',t,y5,'r')
legend('y1','y2','y3','y4','y5')
FIGURES
CONCLUSION:-
The given experiment has been performed successfully.
EXPERIMENT:7
AIM: Solving First, Second and third Order Ordinary Differential Equation using Built-in
Functions and plot.
TOOL USED: MATLAB 7.0
THEORY:
dsolve
S = dsolve(eqn) solves the ordinary differential equation eqn. Here eqn is a symbolic
equation containing diff to indicate derivatives. Alternatively, you can use a string with the
letter D indicating derivatives. For example, syms y(x); dsolve(diff(y) == y +
1) anddsolve('Dy = y + 1','x') both solve the equation dy/dx = y + 1 with respect to the
variable x. Also, eqn can be an array of such equations or strings.
S = dsolve(eqn,cond) solves the ordinary differential equation eqn with the initial or
boundary condition cond.
Solving
Use dsolve to compute symbolic solutions to ordinary differential equations. You can specify
the equations as symbolic expressions containing diff or as strings with the letter D to
indicate differentiation.
Before using dsolve, create the symbolic function for which you want to solve an ordinary
differential equation. Use sym or syms to create a symbolic function. For example, create
a function y(x):
syms y(x)
To specify initial or boundary conditions, use additional equations. If you do not specify
initial or boundary conditions, the solutions will contain integration constants, such
as C1, C2, and so on.
The output from dsolve parallels the output from solve. That is, you can:
Call dsolve with the number of output variables equal to the number of
dependent variables.
Place the output in a structure whose fields contain the solutions of the
differential equations.
PROCEDURE:
Output:
Output:
Output:
EXPERIMENT:8
AIM: Writing brief Scripts starting each Script with a request for input (using input) to
Evaluate the function h(T) using if-else statement, where, h(T) = (T – 10) for 0 < T < 100 =
(0.45 T + 900) for T > 100. Exercise: Testing the Scripts written using A). T = 5, h = -5 and
B). T = 110, h =949.5
THEORY:
Input Funtion:
x = input (prompt) displays the text in prompt and waits for the user to input a value and
press the Return key. The user can enter expressions, like pi/4 or rand(3), and can use
variables in the workspace.
If the user presses the Return key without entering anything, then input returns an
empty matrix.
If the user enters an invalid expression at the prompt, then MATLAB® displays the relevant
error message, and then redisplays the prompt.
Example:
str = input(prompt,'s') returns the entered text as a string, without evaluating the
input as an expression.
Syntax
if expression
statements
elseif expression
statements
else
statements
end
MATLAB PROGRAM:-
T=
h=
-5
T=
110
h=
949.5000
CONCLUSION:-
The given experiment has been performed successfully.
EXPERIMENT:9
AIM: Generating a Square Wave from sum of Sine Waves of certain Amplitude and
Frequencies.
THEORY:
hold on method:
‘hold on’ retains plots in the current axes so that new plots added to the axes do not delete
existing plots. New plots use the next colors and line styles
based on the ColorOrder and LineStyleOrder properties of the axes. MATLAB® adjusts axes
limits, tick marks, and tick labels to display the full range of data.
MATLAB PROGRAM:-
FIGURES
EXPERIMENT:10
AIM: Generating a Square Wave from sum of Sine Waves of certain Amplitude and
Frequencies. Basic 2D and 3D plots: a) parametric space curve. b) polygons with vertices. c)
3D contour lines, pie and bar charts
THEORY:
Contour Plots
A contour plot displays isolines of matrix Z. Label the contour lines using clabel.
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.
bar3 draws a three-dimensional bar graph.
bar3(Y) draws a three-dimensional bar chart, where each element in Y corresponds to one bar.
When Y is a vector, the x-axis scale ranges from 1 to length(Y). When Y is a matrix, the x-axis
scale ranges from 1 to size(Y,1) and the elements in each row are grouped together.
pie(X) draws a pie chart using the data in X. Each slice of the pie chart represents an element
in X.
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.
If sum(X) > 1, then pie normalizes the values by X/sum(X) to determine the area of
each slice of the pie.
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.
pie3(X) draws a three-dimensional pie chart using the data in X. Each element in X is
represented as a slice in the pie chart.
If sum(X) ≤ 1, then the values in X directly specify the area of the pie slices. pie3 draws
only a partial pie ifsum(X) < 1.
If the sum of the elements in X is greater than one, then pie3 normalizes the values
by X/sum(X) to determine the area of each slice of the pie.
Sphere Plot
The sphere function generates the x-, y-, and z-coordinates of a unit sphere for use
with surf and mesh.
sphere generates a sphere consisting of 20-by-20 faces.
sphere(n) draws a surf plot of an n-by-n sphere in the current figure.
[X,Y,Z] = sphere(n) returns the coordinates of a sphere in three matrices that are (n+1)-by-
(n+1) in size. You draw the sphere with surf(X,Y,Z) or mesh(X,Y,Z).
Line Plots
plot3(X1,Y1,Z1,...), where X1, Y1, Z1 are vectors or matrices, plots one or more lines in three-
dimensional space through the points whose coordinates are the elements of X1, Y1, and Z1.
Polygon Plots
Cylinder Plot
cylinder generates x-, y-, and z-coordinates of a unit cylinder. You can draw the cylindrical
object using surf ormesh, or draw it immediately by not providing output arguments.
[X,Y,Z] = cylinder returns the x-, y-, and z-coordinates of a cylinder with a radius equal to 1. The
cylinder has 20 equally spaced points around its circumference.
PROCEDURE:
>> t = 0:pi/50:10*pi;
>> st = sin(t);
>> ct = cos(t);
>> plot3(st,ct,t);
Output:
23Polygons With Vertices
>> t = (1/16:1/8:1)'*2*pi;
>>x = cos(t);
>>y = sin(t);
>>fill(x,y,'g')
>>axis square
Output:
Output:
>> X = [0 1 1 2; 1 1 2 2; 0 0 1 1];
>>Y = [1 1 1 1; 1 0 1 0; 0 0 0 0];
>>Z = [1 1 1 1; 1 0 1 0; 0 0 0 0];
>>C = [0.5000 1.0000 1.0000 0.5000;
1.0000 0.5000 0.5000 0.1667;
0.3330 0.3330 0.5000 0.5000];
>>figure
>>fill3(X,Y,Z,C)
Output:
>>x = -2:0.25:2;
>>[X,Y] = meshgrid(x);
>>Z = X.*exp(-X.^2-Y.^2);
>>contour3(X,Y,Z,30)
Output:
>>x = -2:0.2:2;
>>y = -2:0.2:3;
>>[X,Y] = meshgrid(x,y);
>>Z = X.*exp(-X.^2-Y.^2);
>>figure
contour(X,Y,Z,'ShowText','on')
Output:
>> z = magic(5);
>> b = bar3(z);
>> x = [1,2,3,4,5,6,7,8];
>> pie3(x);
Output:
>> x = [1,2,3,4,5,6,7,8];
>> pie(x);
Output:
>> z = magic(5);
>> b = bar3(z);
Output:
>> figure
>> cylinder
>> z = magic(5);
>> b = bar3(z);
Output: