You are on page 1of 49

BASIC SIMULATION LAB FILE (ES-204)

RAVI KUMAR
A45615820008
B.TECH CE
4THSEM
TABLE OF CONTENTS
DATE OF DATE OF
S.NO. TITLE OF THE EXPERIMENTS
EXPERIMENT SUBMISSION

Creating a One and Two- Dimensional Array (Row /


Column Vector) (Matrix of given size) then,
1. (A). Performing Arithmetic Operations -Addition,
Subtraction, Multiplication and Exponentiation.

(B). Performing Matrix operations -Inverse,


Transpose, Rank with PLOTS

Performing Matrix Manipulations -Concatenating,


Indexing, Sorting, Shifting, Reshaping, Resizing and
Flipping about a Vertical Axis / Horizontal Axis;
2. Creating Arrays X & Y of given size (1 x N) and
Performing

(A). Relational Operations ->, <, ==, <=, >=, ~=

(B). Logical Operations - ~, &, |, XOR

Generating a set of Commands on a given Vector


(Example:X = [1 8 3 9 0 1]) to

(A). Add up the values of the elements (Check


with sum)
3.
(B). Compute the Running Sum (Check with
sum), where Running Sum for element j = the sum
of the elements from 1 to j, inclusive.

(C) Generating a Random Sequence using rand() /


randn() functions and plot them

Evaluating a given expression and rounding it to the


nearest integer value using Round, Floor, Ceil and
Fix functions; Also, generating and Plots of

4. (A) Trigonometric Functions -sin(t),cos(t),


tan(t), sec(t

(B) Logarithmic and other Functions log(A),


log10(A), Square root of A, Real nth root of
A
Creating a vector X with elements, Xn = (-1)n+1/(2n-
1) and Adding up 100 elements of the vector, X;
5. 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.

Generating a Sinusoidal Signal of a given frequency


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

7. Solving First, Second and third Order Ordinary


Differential Equation using Built-in Functions and
plot.

Writing brief Scripts starting each Script with a


request for input (using input) to Evaluate the
8. function h(T) using if-else statement, where,oh(T) =
(T 10) for 0 < T < 100 = (0.45T +900) for T > 100.

Exercise: Testing the Scripts written using A). T = 5,


h = -5and B). T = 110, h =949.5

9. Generating a Square Wave from sum of Sine Waves


of certain Amplitude and Frequencies.

10. Basic 2D and 3D plots: parametric space


curve.polygons with vertices. 3D contour lines, pie
and bar charts
EXPERIMENT:1
AIM: Creating a One-Dimensional Array (Row / Column Vector), Creating a Two-
Dimensional Array (Matrix of given size) and
(A). Performing Arithmetic Operations - Addition, Subtraction, Multiplication and
Exponentiation.
(B). Performing Matrix operations - Inverse, Transpose, Rank.

TOOL USED: MATLAB 7.0

THEORY:

MATLAB is a 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 development, Data acquisition, Modeling,
simulation, and prototyping, Data analysis, exploration, and visualization, Scientific and
engineering graphics, Application development, including graphical user interface
building.

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.

Consider two matrices A and B. If A is an m x n matrix and B is an n x p matrix, they could


be multiplied together to produce an m x n matrix C. Matrix multiplication is possible only
if the number of columns n in A is equal to the number of rows n in B. In matrix
multiplication, the elements of the rows in the first matrix are multiplied with corresponding
columns in the second matrix. Each element in the (i, j)th position, in the resulting matrix C, is
the summation of the products of elements in ith row of first matrix with the corresponding
element in the jth column of the second matrix. In MATLAB, matrix multiplication is
performed by using the
* operator.

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.

Inverse of a matrix A is given by inv(A).

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

AIM: Performing Matrix Manipulations - Concatenating, Indexing, Sorting, Shifting,


Reshaping, Resizing and Flipping about a Vertical Axis / Horizontal Axis; Creating Arrays X
& Y of given size (1 x N) and Performing
(A). Relational Operations - >, <, ==, <=, >=, ~=
(B). Logical Operations - ~, &, |, XOR

TOOL USED: MATLAB 7.0

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

MATLAB allows two different types of arithmetic operations:

 Matrix arithmetic operations

 Array arithmetic operations

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.

Array multiplication. A.*B is the element-by-element product of the arrays


.*
A and B. A and B must have the same size, unless one of them is a scalar.
Slash or matrix right division. B/A is roughly the same as B*inv(A). More
/
precisely, B/A = (A'\B')'.
Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B
./
must have the same size, unless one of them is a scalar.
Backslash or matrix left division. If A is a square matrix, A\B is roughly the
same as inv(A)*B, except it is computed in a different way. If A is an n-by-n
\ matrix and B is a column vector with n components, or a matrix with several
such columns, then X = A\B is the solution to the equation AX = B. A
warning message is displayed if A is badly scaled or nearly singular.
Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A and B
.\
must have the same size, unless one of them is a scalar.
Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer, the
power is computed by repeated squaring. If the integer is negative, X is
^
inverted first. For other values of p, the calculation involves eigenvalues and
eigenvectors, such that if [V,D] = eig(X), then X^p = V*D.^p/V.
Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A
.^
and B must have the same size, unless one of them is a scalar.
Matrix transpose. A' is the linear algebraic transpose of A. For complex
'
matrices, this is the complex conjugate transpose.
Array transpose. A.' is the array transpose of A. For complex matrices, this
.'
does not involve conjugation.

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.

The following table shows the relational operators available in MATLAB:

Operator Description
< Less than
<= Less than or equal to

> Greater than


>= Greater than or equal to
== Equal to
~= Not equal to

Logical Operators

MATLAB offers two types of logical operators and functions:

 Element-wise - these operators operate on corresponding elements of logical arrays.

 Short-circuit - these operators operate on scalar, logical expressions.

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:

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Assume if A = 60; and B = 13; Now in binary format they will be as follows:

A = 0011 1100

B = 0000 1101

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011
MATLAB provides various functions for bit-wise operations like 'bitwise and', 'bitwise or'
and 'bitwise not' operations, shift operation, etc.

The following table shows the commonly used bitwise operations:

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.

The following table shows some commonly used set operations:

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.

setxor Set exclusive OR of two arrays


union Set union of two arrays
unique Unique values in array

MATLAB PROGRAM:-
CONCLUSION:-
The given experiment has been performed successfully.
EXPERIMENT:3

AIM: Generating a set of Commands on a given Vector (Example: X = [1 8 3 9 0 1]) to (A).


Add up the values of the elements (Check with sum) (B). Compute the Running Sum (Check
with sum), where Running Sum for element j = the sum of the elements from 1 to j, inclusive.
(C) Generating a Random Sequence using rand() / randn() functions and plot them.

TOOL USED: MATLAB 7.0

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:

Uniformly distributed random numbers and arrays SyntaxY = rand(n)


Y = rand(m,n)
Y = rand([m n])
Y = rand(m,n,p,...)
Y = rand([m n p...])
Y = rand(size(A))
s = rand('state')

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(m,n) or Y = rand([m n]) returns an m-by-n matrix of random entries.


Y = rand(m,n,p,...) or Y = rand([m n p...]) generates random arrays.

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:

Normally distributed random numbers and arrays SyntaxY = randn(n)


Y = randn(m,n)
Y = randn([m n])
Y = randn(m,n,p,...)
Y = randn([m n p...])
Y = randn(size(A))
randn
s = randn('state')

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.

Y = randn(m,n) or Y = randn([m n]) returns an m-by-n matrix of random entries.

Y = randn(m,n,p,...) or Y = randn([m n p...]) generates random arrays.

Y = randn(size(A)) returns an array of random entries that is the same size as A.


randn, by itself, returns a scalar whose value changes each time it's referenced.

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.

TOOL USED: MATLAB 7.0

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

TOOL USED: MATLAB 7.0

THEORY:

Exponetial function is an elementary function that operates element-wise on arrays. Its


domain includes complex numbers.Y = exp(X) returns the exponential for each element of X.
For complex , it returns the complex exponential.

MATLAB PROGRAM:-

1. Adding upto 100 elements x3

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

COMMAND WINDOW RESULT:-

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.

TOOL USED: MATLAB 7.0

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

Setting Axis Scales

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

xlabel('Time(-0.2 < x < 0)')

ylabel(' Amplitude (sine values)')

title('Graph of sine waves having different time value')

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:

An ordinary differential equation or ODE is an equation containing a function of


one independent variable and its derivatives. The term "ordinary" is used in contrast with the
term partial differential equation which may be with respect to more than one independent
variable.

dsolve

Ordinary differential equation and system solver

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:

>> y = dsolve('Dy = y*x','x');


>> y = dsolve('Dy = y*x','y(1) = 1','x');
>> x = linspace(0,1,20);
>> z = eval(vectorize(y));
>> plot(x,z);

Output:

>> eq1 = 'D3y + 3*D2y + Dy = cos(x)';


>> inits2 = 'y(0)=0, Dy(0)=1,D2y(0)=3';
>> y = dsolve(eq1,inits2,'x');
>> x = linspace(0,1,20);
>> z = eval(vectorize(y));
>> plot(x,z);

Output:

>> eq1 = 'D2y + 8*Dy + 2*y = cos(x)';


>> inits2 = 'y(0)=0, Dy(0)=1';
>> y = dsolve(eq1,inits2,'x');
>> x = linspace(0,1,20);
>> z = eval(vectorize(y));
>> plot(x,z);

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

TOOL USED: MATLAB 7.0

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.

If, Else, Else If Statements:


if expression, statements, end evaluates an expression, and executes a group of statements
when the expression is true. An expression is true when its result is nonempty and
contains only nonzero elements (logical or real numeric). Otherwise, the expression is
false.
The elseif and else blocks are optional. The statements execute only if previous expressions
in the if...end block are false. An if block can include multiple elseif blocks.

Syntax

if expression

statements

elseif expression

statements

else

statements

end
MATLAB PROGRAM:-

%Writing brief Scripts starting each Script h=(T-10)


with a request for input(using input) to
Evaluate the function h(T) using if-else elseif(T>100)
statement, where, h(T) = (T – 10) for 0 < T
< 100 = (0.45 T + 900) for T > 100. h=(0.45*T+900)
Exercise: Testing the Scripts written using
A). T = 5, h = -5 and B). T = 110, h else
=949.5%
disp('Enter a number greater than 0');
T=input('enter the value:')
end
if(T>0 & T<100)

COMMAND WINDOW RESULT:-

>>enter the value:5

T=

h=

-5

>> enter the value:110

T=

110

h=

949.5000

>> enter the value:-98

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.

TOOL USED: MATLAB 7.0

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

%Generating a Square Wave from sum of


Sine Waves of certain Amplitude and plot(t,y,t,z);
Frequencies.%
legend('Sine wave','Square wave')
t=0:0.1:10;
title('Generating square wave from sum of
y=sin(t); sine waves')

z = sin(t) + sin(3*t)/3 + sin(5*t)/5 + xlabel('Time period')


sin(7*t)/7 + sin(9*t)/9;
ylabel('Amplitude')

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

TOOL USED: MATLAB 7.0

THEORY:

Contour Plots

A contour plot displays isolines of matrix Z. Label the contour lines using clabel.

contour(X,Y,Z), contour(X,Y,Z,n), and contour(X,Y,Z,v) draw contour plots


of Z using X and Y to determine the x and y values.
 If X and Y are vectors, then length(X) must equal size(Z,2) and length(Y) must
equal size(Z,1). The vectors must be strictly increasing or strictly decreasing and cannot
contain any repeated values.
 If X and Y are matrices, then their sizes must equal the size of Z. Typically, you should
set X and Y so that the columns are strictly increasing or strictly decreasing and the
rows are uniform (or the rows are strictly increasing or strictly decreasing and the
columns are uniform).
If X or Y is irregularly spaced, then contour calculates contours using a regularly spaced contour
grid, and then transforms the data to X or Y.

contour3 creates a 3-D contour plot of a surface defined on a rectangular grid.

contour3(X,Y,Z), contour3(X,Y,Z,n), and contour3(X,Y,Z,v) draw contour plots


of Z using X and Y to determine the x and y values.
 If X and Y are vectors, then length(X) must equal size(Z,2) and length(Y) must
equal size(Z,1). The vectors must be strictly increasing or strictly decreasing and cannot
contain any repeated values.
 If X and Y are matrices, then their sizes must equal the size of Z. Typically, you should
set X and Y so that the columns are strictly increasing or strictly decreasing and the
rows are uniform (or the rows are strictly increasing or strictly decreasing and the
columns are uniform).
If X or Y is irregularly spaced, then contour3 calculates contours using a regularly
spaced contour grid, and then transforms the data to X or Y.

Bar Graph Plot

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 Chart Plot

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

The plot3 function displays a three-dimensional plot of a set of data points.

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

The fill function creates colored polygons.


fill(X,Y,C) creates filled polygons from the data in X and Y with vertex color specified
by C. C is a vector or matrix used as an index into the colormap. If C is a row
vector, length(C) must equal size(X,2) and size(Y,2); if C is a column vector, length(C) must
equal size(X,1) and size(Y,1). If necessary, fill closes the polygon by connecting the last vertex
to the first.

The fill3 function creates flat-shaded and Gouraud-shaded polygons.

fill3(X,Y,Z,C) fills three-dimensional polygons. X, Y, and Z triplets specify the polygon


vertices. If X, Y, or Z is a matrix, fill3 creates n polygons, where n is the number of columns in
the matrix. fill3 closes the polygons by connecting the last vertex to the first when necessary.

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:

Parametric Space Curves

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

>>patch([0 0 1 1],[0 1 1 0],


[1 1 1 1],'r')
>>patch([0 1 1 0],[0 0 0 0],
[0 0 1 1],'r')
>>patch([0 0 0 0],[0 1 1 0],
[0 0 1 1],'r')
>>view(-37.5, 30)
>>axis square

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:

3-D Contour Lines, Pi Charts and Bar Graphs

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

You might also like