You are on page 1of 53

BASIC SIMULATION LAB FILE (4MAE5-Y)

Submitted By:
Keshav Poddar
(A2325313006)
4MAE-5(Y)

Submitted To:
Mr. Devesh Kumar
(Assistant Professor)

TABLE OF CONTENTS

S.NO.

TITLE OF THE EXPERIMENTS

1.

Creating a One and Two- Dimensional Array (Row /


Column Vector) (Matrix of given size) then,
(A). Performing Arithmetic Operations -Addition,
Subtraction, Multiplication and Exponentiation.
(B). Performing Matrix operations -Inverse, Transpose,
Rank with PLOTS

2.

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

3.

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

4.

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

5.

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.

6.

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.

DATE OF
EXPERIMENT

DATE OF
SUBMISSION

7.

8.

9.

10.

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 function h(T)
using if-else statement, where,oh(T) = (T10) 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
Generating a Square Wave from sum of Sine Waves of
certain Amplitude and Frequencies.
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 TwoDimensional 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:%creating one dimensional row matrix of


order 1*3%

%performing arithmetic operation-addition


%

a=[2,3,4];

display('arithmetic operation-addition')

b=[6,7,5];
%creating one dimensional column matrix
of order 3*1%
c=[3;4;5];
d=[5;9;8];
%creating two dimensional row matrix
2*4%
e=[2,5,4,5;2,3,9,6] ;

h=e+f
%performing
subtraction%

arithmetic

operation-

%performing
arithmetic
multiplication%

operation-

i=e-f

j=e*g

f=[2,3,4,5;2,4,7,6];

%performing
arithmetic
exponentiation%

%creating two dimensional column matrix


4*2%

k=2.^a

g=[2,3;4,5;2,4;7,6] ;

m=0:1:2

operation-

stem(m,k)

x=[2,3,4;4,6,5;5,6,7]

%performing matrix operation-inverse%


p=inv(x)
%performing matrix operation-transpose%
v=g'
%performing matrix operation-rank%
rank(e)

COMMAND WINDOW RESULT:h=

k=

10

16

m=

i=

16

0
0

-1

j=

x=

67

77

76

93

v=
p=
-1.3333 -0.3333
0.3333

1.0000

0.6667 -0.6667

0.6667 -0.3333

FIGURES

ans =
2

EXPONENTIAL FUNCTION

16
14
12

y-axis

10
8
6
4
2
0

0.2

0.4

0.6

0.8

1
x-axis

1.2

1.4

1.6

1.8

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

p&q

p|q

p^q

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

bitshift(a, k)

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

intersect(A,B)

Set intersection of two arrays; returns the values common to both A


and B. The values returned are in sorted order.

intersect(A,B,'rows')

Treats each row of A and each row of B as single entities and returns
the rows common to both A and B. The rows of the returned matrix
are in sorted order.

ismember(A,B)

Returns an array the same size as A, containing 1 (true) where the


elements of A are found in B. Elsewhere, it returns 0 (false).

ismember(A,B,'rows')

Treats each row of A and each row of B as single entities and returns a
vector containing 1 (true) where the rows of matrix A are also rows of
B. Elsewhere, it returns 0 (false).

issorted(A)

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 1by-N cell array of strings. A is considered to be sorted if A and the
output of sort(A) are equal.

sorted order, and logical 0 (false) otherwise. Matrix A is considered to


be sorted if A and the output of sortrows(A) are equal.
setdiff(A,B)

setdiff(A,B,'rows')

Set difference of two arrays; returns the values in A that are not in 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
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:%generating two matrices%

i=rot90(g)

a=[2 4 3;5 6 8;9 8 7]


b=[2 5 8;5 9 4; 4 7 5]

% flipping a matrix%

% concatenate two matrices%


display('horizontal concatenation')
c=[a b]
display('vertical concatenation')
c=[a;b]

display('flipping a matrix')
j=fliplr(i)
% resizing a matrix%
display(' resizing a matrix')
g(2,:)=[]
g(:,2)=[]

%indexing two matrices%


% shifting the matrix%
display('indexing two matrices')
d=b(a)
%sorting arrays
display('sorting row wise')
f=sort(a,1)
display('sorting column wise')
f=sort(a,2)
% reshaping the matrix%
h=[2 3 4 5;8 1 2 0;6 9 3 7]
display('reshaping the matrix')
g=reshape(h,2,6)
% rotating a matrix%
display('rotating a matrix')

display(' shifting a matrix')


k=rand(4)
l=circshift(k, [1, 3])
%using relational operators(>, <, ==, <=,
>=, ~=)%
X = 5;
display(' using >= operator')
X >= [9 2 3; 4 5 6; 7 8 10]
display(' using <= operator')
X <= [9 2 3; 4 5 6; 7 8 10]
display(' using ~= operator')
X ~= [9 2 3; 4 5 6; 7 8 10]
display(' using >operator')
X > [9 2 3; 4 5 6; 7 8 10]

display(' using < operator')


X < [9 2 3; 4 5 6; 7 8 10]
% using logical operations%
m=[1 5;8 0]
n=[2 0; 0 5]
display(' using and operator')

and(m,n)
display(' using not operator')
~m
display(' using or operator')
or(m,n)
display(' using xor operator')
xor(m,n)

COMMAND WINDOW RESULT:a=


2
5
9

4
6
8

3
8
7

b=
2
5
4

5
9
7

8
4
5

horizontal concatenation
c=
2 4 3 2 5 8
5 6 8 5 9 4
9 8 7 4 7 5
vertical concatenation
c=
2 4 3
5 6 8
9 8 7
2 5 8
5 9 4
4 7 5
indexing two matrices
d=
5 5 4
9 7 4
5 4 8
sorting row wise
f=
2 4 3
5 6 7
9 8 8
sorting column wise
f=
2 3 4
5 6 8
7 8 9

h=
2 3 4 5
8 1 2 0
6 9 3 7
reshaping the matrix
g=
2 6 1 4 3
8 3 9 2 5
rotating a matrix

0
7

i=
0 7
3 5
4 2
1 9
6 3
2 8
flipping a matrix
j=
7 0
5 3
2 4
9 1
3 6
8 2
resizing a matrix
g=
2 6 1 4 3 0
g=
2 1 4 3 0
shifting a matrix
k=
0.1875 0.7690 0.6733
0.2662 0.3960 0.4296
0.7978 0.2729 0.4517
0.4876 0.0372 0.6099
l=

0.0594
0.3158
0.7727
0.6964

0.0372
0.7690
0.3960
0.2729

0.6099
0.6733
0.4296
0.4517

using >= operator


ans =
0 1 1
1 1 0
0 0 0
using <= operator
ans =
1 0 0
0 1 1
1 1 1
using ~= operator
ans =
1 1 1
1 0 1
1 1 1
using >operator
ans =
0 1 1
1 0 0
0 0 0
using < operator

0.6964
0.0594
0.3158
0.7727

0.4876
0.1875
0.2662
0.7978

ans =
1 0 0
0 0 1
1 1 1
m=
1 5
8 0
n=
2 0
0 5
using and operator
ans =
1 0
0 0
using not operator
ans =
0 0
0 1
using or operator
ans =
1 1
1 1
using xor operator
ans =
0 1
1 1

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

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:

1. ADD VALUES IN A VECTOR:


>> sum = 0;
for i = 1:5
sum = sum+i;
end
display(sum)
OUTPUT
sum =
15
2. CHECK SUM:
>> A = [1 2 3 4 5]
OUTPUT
A=
1

>> B = sum(A)
OUTPUT
B=
15
3. CHECK RUNNING SUM:
>> sum = 0;
>> for i = 1:5
sum = sum+i;
display(sum)
end
OUTPUT
sum =
1
sum =
3
sum =
6
sum =
10
sum =
15

4. CHECK CUMSUM:
>> A = [1 2 3 4 5]
OUTPUT
A=
1 2 3 4 5
>> B = cumsum(A)
OUTPUT
B=
1

10

15

5. RANDOM:

>> B = rand(3)
OUTPUT
B=
0.4447
0.6154
0.7919
>> plot(B)

0.9218
0.7382
0.1763

0.4057
0.9355
0.9169

>> B = randn(3)
OUTPUT
B=
0.1746 -0.5883
-0.1867 2.1832
0.7258 -0.1364
>> plot(B)

0.1139
1.0668
0.0593

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:
1. Evaluate given expression and round it to the nearest integer value using
1. ROUND

>>round(3.67)
OUTPUT
ans =
4
2. FLOOR
>>floor(3.67)
OUTPUT
ans =
3
3. CEIL
>>ceil(3.67)
OUTPUT
ans =
4
4. FIX
>>a = [1.88 2.05 9.54 8.5]
OUTPUT
a=
1.8800
>>fix(a)
ans =
1
2

2.0500

9.5400

8.5000

2. Generate plots of:


TRIGONOMETRIC FUNCTIONS
1. sin(t)
>> x=(0:0.01:2*pi);
>> y=sin(x);
>>plot(x,y);

OUTPUT

2. cos(t)
>> x=(0:0.01:2*pi);
>> y=cos(x);
>>plot(x,y);
OUTPUT

3. cosec(t)
>> x=(0:0.01:2*pi);
>> y=csc(x);
Warning: Divide by zero.
> In csc at 14
>>plot(x,y);
OUTPUT

4. sec(t)
>> x=(0:0.01:2*pi);
>> y=sec (x);
>>plot(x,y);
OUTPUT

5. tan(t)
>> x=(0:0.01:2*pi);
>> y=sin(x);
>>plot(x,y);
OUTPUT

6. cot(t)
>> x=(0:0.01:2*pi);
>> y=cot(x);
Warning: Divide by zero.
> In cot at 14
>>plot(x,y);
OUTPUT

3. LOGARITHMIC FUNCTIONS
1

log(t)

>> x=(0:0.01:20)
>> plot(log(x))
Warning: Log of zero
OUTPUT

2. log10(t)
>> x=(0.01:0.01:20)
>> plot(log(x))
OUTPUT

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


2. >> n = 1:100;

12. plot(a(1,1:4))
13.

3.

x = ( (-1).^(n+1) ) ./ (2*n - 1);

14. Exp(x)

4.

y = sum(x)

5.

15. b=exp(x)
16. plot(b(1,1:4))
17.

6. x

18.

7.
8. plot(x(1,1:4))
9.

19.

21.

10. x3
11. a=x.^3;
24.

25. COMMAND WINDOW RESULT:26. y =


27.

20. Exp(n2)

0.7829

28.
29.
30. FIGURES

22. c=exp(x.^2);
23. plot(c(1,1:4))

31.
32.

33. CONCLUSION:34. The given experiment has been performed successfully.


35.
36.
37.
38.
39.
40.
41.
42.
43.
44.

45. EXPERIMENT:6
46.

47. 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.
48.
49. TOOL USED: MATLAB 7.0
50.
51. THEORY:
52.
53. The sin function operates element-wise on arrays. The function's domains and ranges
include complex values. All angles are in radians.
54. Y = sin(X) returns the circular sine of the elements of X.
55. 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.


56.

Setting Colors on Graph

57.
MATLAB provides eight basic color options for drawing graphs. The
following table shows the colors and their codes:
58. Color

59. Code

60. White

61. w

62. Black

63. k

64. Blue

65. b

66. Red

67. r

68. Cyan

69. c

70. Green

71. g

72. Magenta

73. m

74. Yellow

75. y

76.

77.

Setting Axis Scales

78. 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:
79. axis ( [xmin xmax ymin ymax] )
80.
81.

Generating Sub-Plots

82. 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.
83. Syntax for the command is:
84. subplot(m, n, p)
85. where, m and n are the number of rows and columns of the plot array and p specifies
where to put a particular plot.
86.
87.
88.
89.

90. MATLAB PROGRAM:91.


92. %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. %
93.
94. t=-0.25:0.0001:0.25;
95. f1=3;
96. y1=sin(2*pi*f1*t);
106.

107.
108.
109.
110.
111.

97. y2=sin(2*pi*f1*2*t);
98. y3=sin(2*pi*f1*4*t);
99. y4=sin(2*pi*f1*0.25*t);
100. y5=sin(2*pi*f1*0.625*t);
101. plot(t,y1,'k',t,y2,'g',t,y3,'b',t,y4,'m',t,
y5,'r')
102. xlabel('Time(-0.2 < x < 0)')
103. ylabel(' Amplitude (sine values)')
104. title('Graph of sine waves having
different time value')
105. legend('y1','y2','y3','y4','y5')

112.
113.
114.
115.
116.
117.
118.
119.
120.
121.

FIGURES

122.

123. CONCLUSION:-

124.

The given experiment has been performed successfully.

125.

EXPERIMENT:7
126.

127. AIM: Solving First, Second and third Order Ordinary Differential Equation using
Built-in Functions and plot.
128. TOOL USED: MATLAB 7.0
129.
130. THEORY:
131.
132. 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.
133.
134.
135.

dsolve

136. Ordinary differential equation and system solver


137.
138. 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.
139.
140. S = dsolve(eqn,cond) solves the ordinary differential equation eqn with the initial or
boundary condition cond.
141.
142. Solving
143. 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.
144.
145. 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):
146. syms y(x)
147.
148. 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.
149. 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.
150.

151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.

166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.

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

183.
184.
185.

186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.

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:

213.
214.

215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.

231.
232. EXPERIMENT:8
233.
234. 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
235.
236.
237.
238.
239.
240.

TOOL USED: MATLAB 7.0


THEORY:
Input Funtion:

241. 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.
242.

Example:

243. str = input(prompt,'s') returns the entered text as a string, without evaluating the
input as an expression.
244.
245.

If, Else, Else If Statements:

246. 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.
247. 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.
248.
249. Syntax
250.

if expression

251.

statements

252.

elseif expression

253.
254.
255.
256.

statements
else
statements
end

257. MATLAB PROGRAM:258.

259. %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%
260.
261. T=input('enter the value:')
262.
263. if(T>0 & T<100)

264.
265.
h=(T-10)
266.
267. elseif(T>100)
268.
269.
h=(0.45*T+900)
270.
271.
else
272.
273.
disp('Enter a number greater than
0');
274.
275. end
276.

277.
278.

279. COMMAND WINDOW RESULT:280.

281.

>>enter the value:5

282.
283.

294.
T=

284.
285.

293.

295.
296.

298.

287.

299.
h=

289.
290.
291.
292.
304.

949.5000

302.
303.

>> enter the value:110

h=

300.
301.

-5

110

297.

286.

288.

T=

>> enter the value:-98

305.

306. CONCLUSION:307.

The given experiment has been performed successfully.

308.

309. EXPERIMENT:9
310.
311. AIM: Generating a Square Wave from sum of Sine Waves of certain Amplitude and
Frequencies.
312.
313. TOOL USED: MATLAB 7.0
314.
315. THEORY:
316.
317. hold on method:
318. 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.
319.
320.

321. MATLAB PROGRAM:322.


323.

324. %Generating a Square Wave from


sum of Sine Waves of certain
Amplitude and Frequencies.%
325.
326. t=0:0.1:10;
327.
328. y=sin(t);
329.
330. z = sin(t) + sin(3*t)/3 + sin(5*t)/5
+ sin(7*t)/7 + sin(9*t)/9;
331.
332. plot(t,y,t,z);
333.
334. legend('Sine wave','Square wave')
335.
336. title('Generating square wave from
sum of sine waves')
337.
338. xlabel('Time period')
339.

340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.

ylabel('Amplitude')

352.

358.

353.

359.

354.

360.

355.

361.

356.

362.

357.

363. FIGURES

364.
365.

366. EXPERIMENT:10
367.
368. 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
369.
370. TOOL USED: MATLAB 7.0
371.
372. THEORY:
373.
374. Contour Plots
375.
376. A contour plot displays isolines of matrix Z. Label the contour lines using clabel.
377.
378. 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).
379. 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.
380.
381. contour3 creates a 3-D contour plot of a surface defined on a rectangular grid.
382.
383. 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).
384. 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.
385.
386. Bar Graph Plot
387.
388. 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.
389.

390. bar3 draws a three-dimensional bar graph.


391.
392. 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.
393.
394. Pie Chart Plot
395.

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

397.
398. 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.
399.
400. Sphere Plot
401.
402. The sphere function generates the x-, y-, and z-coordinates of a unit sphere for use
with surf and mesh.
403. sphere generates a sphere consisting of 20-by-20 faces.
404. sphere(n) draws a surf plot of an n-by-n sphere in the current figure.
405. [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).
406.
407.
408. Line Plots
409.
410. The plot3 function displays a three-dimensional plot of a set of data points.
411.
412. 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.
413.
414. Polygon Plots
415.
416. The fill function creates colored polygons.

417.
418. 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.
419.
420. The fill3 function creates flat-shaded and Gouraud-shaded polygons.
421.
422. 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.
423.
424. Cylinder Plot
425.
426. 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.
427. [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.
428.
429. PROCEDURE:
430.
431.

Parametric Space Curves

432.
433.
434.
435.
436.
437.
438.
439.
440.

>> t = 0:pi/50:10*pi;
>> st = sin(t);
>> ct = cos(t);
>> plot3(st,ct,t);
Output:

441.
442.
443.
444.
445.
446.
447.
448.
449.
450.
451.
452.
453.
454.
455.
456.
457.
458.
459.
460.
461.
462.
463.
464.
465.
466.

Polygons 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],

467. [1 1 1 1],'r')
468. >>patch([0 1 1 0],[0 0 0 0],
469. [0 0 1 1],'r')
>>patch([0 0 0 0],[0 1 1 0],
470. [0 0 1 1],'r')
471. >>view(-37.5, 30)
472. >>axis square
473.
474. Output:
475.
476.
477.
478.
479.
480.
481.
482.
483.
484.
485.
486.
487.
488. >> X = [0 1 1 2; 1 1 2 2; 0 0 1 1];
489. >>Y = [1 1 1 1; 1 0 1 0; 0 0 0 0];
490. >>Z = [1 1 1 1; 1 0 1 0; 0 0 0 0];
491. >>C = [0.5000 1.0000 1.0000
0.5000;
492.
1.0000 0.5000 0.5000
0.1667;
493.
0.3330 0.3330 0.5000
0.5000];
494. >>figure
495. >>fill3(X,Y,Z,C)
496.
497. Output:
498.
499.
500.
501.
502.
503.
504.
505.
506.
507.
508. 3-D Contour Lines, Pi Charts and Bar Graphs
509.
510.
>>x = -2:0.25:2;

511.
512.
513.
514.
515.
516.
517.
518.
519.
520.
521.
522.
523.
524.
525.
526.
527.
528.
529.
530.
531.
532.
533.
534.
535.
536.
537.
538.
539.
540.
541.
542.
543.
544.
545.
546.
547.
548.
549.
550.
551.
552.
553.
554.

>>[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];

555.
556.
557.
558.
559.
560.
561.
562.
563.
564.
565.
566.
567.
568.
569.
570.
571.
572.
573.
574.
575.
576.
577.
578.
579.
580.
581.
582.
583.
584.
585.
586.
587.
588.
589.
590.
591.
592.
593.
594.
595.
596.
597.
598.
599.

>> pie3(x);
Output:

>> x = [1,2,3,4,5,6,7,8];
>> pie(x);
Output:

600.
601.
602.
603.
604.
605.
606.
607.
608.
609.
610.
611.
612.
613.
614.
615.
616.
617.
618.
619.
620.
621.
622.
623.
624.
625.
626.
627.
628.
629.
630.
631.

>> z = magic(5);
>> b = bar3(z);
Output:

>> figure
>> cylinder

>> z = magic(5);
>> b = bar3(z);
Output:

632.

You might also like