Computational Lab (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

B.I.T.

Sindri, Dhanbad
Department of Electrical Engineering

Name of Lab: Computational Lab

S. L. No. Name of Experiment


Experiment 1 Using MATLAB as a Calculator
Experiment 2 Managing the Workspace
Experiment 3 Mathematical function and its Operations
Experiment 4 Curve Plotting, Labeling and its Analysis
Experiment 5 Matrix generation
Experiment 6 Solving linear equations
Experiment 7 Scientific Computation
Experiment 8 Logical Operation
Experiment 9 Laplace Transform of Symbolic Expression
Experiment 10 Solution of Eigen values and Eigen Vector of a matrix
Experiment 1: Using MATLAB as a calculator
As an example of a simple interactive calculation, just type the expression you want to evaluate.
Let’s start at the very beginning. For example, let’s suppose you want to calculate the expression,
1 + 2 × 3. You type it at the prompt command (>>) as follows,

>> 1+2*3

ans = 7

You will have noticed that if you do not specify an output variable, MATLAB uses a default
variable ans, short for answer, to store the results of the current calculation. Note that the
variable ans is created (or overwritten, if it is already existed). To avoid this, you may assign a
value to a variable or output argument name.

For example, >> x = 1+2*3 x = 7

will result in x being given the value 1 + 2 × 3 = 7. This variable name can always be used to
refer to the results of the previous computations.

Therefore, computing 4x will result in

>> 4*x

ans = 28.0000

Before we conclude this minimum session, Table 1.1 gives the partial list of arithmetic operators.

Table 1.1: Basic arithmetic operators

Symbol Operation Example

+ Addition 2+3
- Subtraction 3-2
* Multiplication 2*3
/ Division 3/2

For operators of equal precedence, evaluation is from left to right. Now, consider another
example:

In MATLAB, it becomes

>> 1/(2+3^2)+4/5*6/7
ans = 0.7766

or, if parentheses are missing,

>> 1/2+3^2+ 4/5 * 6/7

ans = 10.1857

So here what we get: two different results. Therefore, we want to emphasize the importance of
precedence rule in order to avoid ambiguity.
Experiment 2: Managing the Workspace
The contents of the workspace persist between the executions of separate commands. Therefore,
it is possible for the results of one problem to have an effect on the next one. To avoid this
possibility, it is a good idea to issue a clear command at the start of each new independent
calculation.

>> clear

The command clear or clear all removes all variables from the workspace. This frees up system
memory. In order to display a list of the variables currently in the memory, type

>> who

while, whos will give more details which include size, space allocation, and class of the
variables.

Keeping track of your work session

It is possible to keep track of everything done during a MATLAB session with the diary
command. >> diary or give a name to a created file,

>> diary

FileName where FileName could be any arbitrary name you choose.

The function diary is useful if you want to save a complete MATLAB session. They save all
input and output as they appear in the MATLAB window. When you want to stop the recording,
enter diary off. If you want to start recording again, enter diary on. The file that is created is a
simple text file. It can be opened by an editor or a word processing program and edited to
remove extraneous material, or to add your comments. You can use the function type to view the
diary file or you can edit in a text editor or print. This command is useful, for example in the
process of preparing a homework or lab submission.

Miscellaneous commands Here are few additional useful commands:

• To clear the Command Window, type clc

• To abort a MATLAB computation, type ctrl-c

• To continue a line, type . . .


Getting help

To view the online documentation, select MATLAB Help from Help menu or MATLAB Help
directly in the Command Window. The preferred method is to use the Help Browser. The Help
Browser can be started by selecting the ? icon from the desktop toolbar. On the other hand,
information about any command is available by typing

>> help Command

Another way to get help is to use the lookfor command. The lookfor command differs from the
help command. The help command searches for an exact function name match, while the lookfor
command searches the quick summary information in each function for a match. For example,
suppose that we were looking for a function to take the inverse of a matrix. Since MATLAB
does not have a function named inverse, the command help inverse will produce nothing. On the
other hand, the command lookfor inverse will produce detailed information, which includes the
function of interest, inv.

>> lookfor inverse

Note - At this particular time of our study, it is important to emphasize one main point. Because
MATLAB is a huge program; it is impossible to cover all the details of each function one by one.
However, we will give you information how to get help.

Here are some examples:

• Use on-line help to request info on a specific function

>> help sqrt

• In the current version (MATLAB version 7), the doc function opens the on-line version of the
help manual. This is very helpful for more complex commands.

>> doc plot

• Use lookfor to find functions by keywords. The general form is

>> lookfor FunctionName


Experiment 3: Mathematical functions and its operation

There is a long list of mathematical functions that are built into MATLAB. These functions are called
x
built-ins. Many standard mathematical functions, such as sin(x), cos(x), tan(x), e , ln(x), are evaluated
by the functions sin, cos, tan, exp, and log respectively in

MATLAB

cos(x) Cosine abs(x) Absolute value


sin(x) Sine sign(x) Signum function
tan(x) Tangent max(x) Maximum value
acos(x) Arc cosine min(x) Minimum value
asin(x) Arc sine ceil(x) Round towards +1

atan(x) Arc tangent floor(x) Round towards ¡1


exp(x) Exponential round(x) Round to nearest integer
sqrt(x) Square root rem(x) Remainder after division
log(x) Natural logarithm angle(x) Phase angle
log10(x) Common logarithm conj(x) Complex conjugate

We illustrate here some typical examples which related to the elementary functions previously defined.

As a first example, the value of the expression

y = e (−a) sin(x) + 10√y,

for a = 5, x = 2, and y = 8

is computed by

>> a = 5; x = 2; y = 8;

>> y = exp(-a)*sin(x)+10*sqrt(y) y = 28.2904

The subsequent examples are

>> log(142)
ans = 4.9558

>> log10(142)

ans = 2.1523

Note the difference between the natural logarithm log(x) and the decimal logarithm (base 10) log10(x).
To calculate sin(π/4) and e 10, we enter the following commands in MATLAB,

>> sin(pi/4)

ans = 0.7071

>> exp(10)

ans = 2.2026e+004
Experiment 4: Curve Plotting, Labeling and its analysis

The MATLAB command to plot a graph is plot(x,y).

The vectors x = (1, 2, 3, 4, 5, 6) and y = (3, −1, 2, 4, 5, 1) produce the picture shown in Figure 2.1.

>> x = [1 2 3 4 5 6];

>> y = [3 -1 2 4 5 1];

>> plot(x,y)

Note: The plot functions has different forms depending on the input arguments. If y is a vector plot(y)
produces a piecewise linear graph of the elements of y versus the index of the elements of y. If we specify
two vectors, as mentioned above, plot(x,y) produces a graph of y versus x. For example, to plot the
function sin (x) on the interval [0, 2π], we first create a vector of x values ranging from 0 to 2π, then
compute the sine of these values, and finally plot the result:

>> x = 0:pi/100:2*pi;

>> y = sin(x);

>> plot(x,y)

Notes: • 0:pi/100:2*pi

yields a vector that – starts at 0, – takes steps (or increments) of π/100, – stops when 2π is reached. • If
you omit the increment, MATLAB automatically increments by 1.

MATLAB enables you to add axis labels and titles. For example, using the graph from the previous
example, add an x- and y-axis labels. Now label the axes and add a title. The character \pi creates the
symbol π. An example of 2D plot is shown in Figure 2.2.

>> xlabel(’x = 0:2\pi’)

>> ylabel(’Sine of x’)

>> title(’Plot of the Sine function’)

Multiple (x, y) pairs arguments create multiple graphs with a single call to plot. For example, these
statements plot three related functions of x: y1 = 2 cos(x), y2 = cos(x), and y3 = 0.5 cos(x), in the
interval 0 ≤ x ≤ 2π.

>> x = 0:pi/100:2*pi;

>> y1 = 2*cos(x);
>> y2 = cos(x);

>> y3 = 0.5*cos(x);

>> plot(x,y1,’--’,x,y2,’-’,x,y3,’:’)

>> xlabel(’0 \leq x \leq 2\pi’)

>> ylabel(’Cosine functions’)

>> legend(’2*cos(x)’,’cos(x)’,’0.5*cos(x)’)

>> title(’Typical example of multiple plots’)

>> axis([0 2*pi -3 3])


Experiment 5: Matrix generation
Matrices are fundamental to MATLAB. Therefore, we need to become familiar with matrix generation
and manipulation. Matrices can be generated in several ways. 2.5.1 Entering a vector A vector is a special
case of a matrix. The purpose of this section is to show how to create vectors and matrices in MATLAB.
As discussed earlier, an array of dimension 1 ×n is called a row vector, whereas an array of dimension m
× 1 is called a column vector. The elements of vectors in MATLAB are enclosed by square brackets and
are separated by spaces or by commas. For example, to enter a row vector, v, type

>> v = [1 4 7 10 13] v = 1 4 7 10 13

Column vectors are created in a similar way, however, semicolon (;) must separate the components of a
column vector,

>> w = [1;4;7;10;13]

w = 1 4 7 10 13

On the other hand, a row vector is converted to a column vector using the transpose operator. The
transpose operation is denoted by an apostrophe or a single quote (’).

>> w = v’ w = 1 4 7 10 13

Thus, v(1) is the first element of vector v, v(2) its second element, and so forth. Furthermore, to access
blocks of elements, we use MATLAB’s colon notation (:). For example, to access the first three elements
of v, we write,

>> v(1:3) ans = 1 4 7

Or, all elements from the third through the last elements,

>> v(3,end) ans = 7 10 13 where end signifies the last element in the vector. If v is a vector, writing

>> v(:) produces a column vector, whereas writing

>> v(1:end) produces a row vector.

Entering a matrix
To enter a matrix A, such as, A = [1 2 3 4 5 6 7 8 9]

>> A = [1 2 3; 4 5 6; 7 8 9]

MATLAB then displays the 3 × 3 matrix as follows, A = 1 2 3 4 5 6 7 8 9 Note that the use of semicolons
(;) here is different from their use mentioned earlier to suppress output or to write multiple commands in a
single line. Once we have entered the matrix, it is automatically stored and remembered in the
Workspace. We can refer to it simply as matrix A. We can then view a particular element in a matrix by
specifying its location. We write,

>> A(2,1) ans = 4 A(2,1) is an element located in the second row and first column. Its value is 4.

We select elements in a matrix just as we did for vectors, but now we need two indices. The element of
row i and column j of the matrix A is denoted by A(i,j). Thus, A(i,j) in MATLAB refers to the element
Aij of matrix A. The first index is the row number and the second index is the column number. For
example, A(1,3) is an element of first row and third column. Here, A(1,3)=3. Correcting any entry is easy
through indexing. Here we substitute A(3,3)=9 by A(3,3)=0. The result is

>> A(3,3) = 0 A = 1 2 3 4 5 6 7 8 0

2.5.8 Deleting row or column

To delete a row or column of a matrix, use the empty vector operator, [ ].

>> A(3,:) = [] A = 1 2 3 4 5 6

Third row of matrix A is now deleted. To restore the third row, we use a technique for creating a matrix
>> A = [A(1,:);A(2,:);[7 8 0]] A = 1 2 3 4 5 6 7 8 0

Matrix A is now restored to its original form.


Experiment 6: Solving linear equations
One of the problems encountered most frequently in scientific computation is the solution of
systems of simultaneous linear equations. With matrix notation, a system of simultaneous linear
equations is written

Ax = b

where there are as many equations as unknown. A is a given square matrix of order n, b is a
given column vector of n components, and x is an unknown column vector of n components. In
linear algebra we learn that the solution to Ax = b can be written as x = A−1 b, where A−1 is the
inverse of A. For example, consider the following system of linear equations

x + 2y + 3z = 1

4x + 5y + 6z = 1

7x + 8y = 1

The coefficient matrix A is A = [1 2 3 4 5 6 7 8 9] and the vector b =[1 1 1] With matrix


notation, a system of simultaneous linear equations is written Ax = b. This equation can be
solved for x using linear algebra. The result is x = A−1 b. There are typically two ways to solve
for x in MATLAB:

1. The first one is to use the matrix inverse, inv.

>> A = [1 2 3; 4 5 6; 7 8 0];

>> b = [1; 1; 1];

>> x = inv(A)*b

x = -1.0000 1.0000 -0.0000

2. The second one is to use the backslash (\)operator. The numerical algorithm behind this
operator is computationally efficient. This is a numerically reliable way of solving system
of linear equations by using a well-known process of Gaussian elimination.

>> A = [1 2 3; 4 5 6; 7 8 0];

>> b = [1; 1; 1];

>> x = A\b

x = -1.0000 1.0000 -0.0000


Experiment 7: Scientific Computation

Plot the following cosine functions,

y1 = 2 cos(x), y2 = cos(x), and y3 = 0.5 cos(x), in the interval 0 ≤ x ≤ 2π. This example has
been presented in previous Chapter. Here we put the commands in a file.

x = 0: pi/100:2*pi;

y1 = 2*cos(x);

y2 = cos(x);

y3 = 0.5*cos(x);

plot(x,y1,’--’,x,y2,’-’,x,y3,’:’)

xlabel(’0 \leq x \leq 2\pi’)

ylabel(’Cosine functions’)

legend(’2*cos(x)’,’cos(x)’,’0.5*cos(x)’)

title(’Typical example of multiple plots’)

axis([0 2*pi -3 3])


Experiment 8: Logical operation

Let us illustrate the “if” statement through a simple example. Suppose we would like to
define and plot the piecewise defined function

This is done with the use of the “if” statement in MATLAB as follows. First we define the
“domain” vector x from –1 to 1 with increment 0.01 to produce a smooth enough curve.

» x=-1:0.01:1;

Next, we loop through the values of x and for each one we create the corresponding function
value F as a vector.

» for i=1:length(x)

if x(i) < 0.5

F(i) = x(i)^2;

else

F(i) = 0.25;

end

end

Finally, we plot the two vectors (using a solid black curve).

» plot(x, F,’-k’)
Experiment 9: Laplace Transform of Symbolic Expression

Aim : Compute the Laplace transform of exp(-a*t).

Compute the Laplace transform of 1/sqrt(x).

By default, the independent variable is t, and the transformation variable is s.

syms a t
f = exp(-a*t);
laplace(f)

syms x y
f = 1/sqrt(x);
laplace(f)

ans =
1/(a + s)

ans =
pi^(1/2)/s^(1/2)
Experiment 10: Solution of Eigen values and Eigen Vector of a matrix

Use gallery to create a symmetric positive definite matrix.

A = gallery('lehmer',4)

A = 4×4

1.0000 0.5000 0.3333 0.2500


0.5000 1.0000 0.6667 0.5000
0.3333 0.6667 1.0000 0.7500
0.2500 0.5000 0.7500 1.0000

Calculate the eigenvalues of A. The result is a column vector.

e = eig(A)

e = 4×1

0.2078
0.4078
0.8482
2.5362

Alternatively, use eigvalOption to return the eigenvalues in a diagonal matrix.

D = eig(A,'matrix')

D = 4×4

0.2078 0 0 0
0 0.4078 0 0
0 0 0.8482 0
0 0 0 2.5362

Use gallery to create a circulant matrix.

A = gallery('circul',3)
A = 3×3

1 2 3
3 1 2
2 3 1

Calculate the eigenvalues and right eigenvectors of A.


[V,D] = eig(A)

V = 3×3 complex

-0.5774 + 0.0000i 0.2887 - 0.5000i 0.2887 + 0.5000i


-0.5774 + 0.0000i -0.5774 + 0.0000i -0.5774 + 0.0000i
-0.5774 + 0.0000i 0.2887 + 0.5000i 0.2887 - 0.5000i

D = 3×3 complex

6.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i


0.0000 + 0.0000i -1.5000 + 0.8660i 0.0000 + 0.0000i
0.0000 + 0.0000i 0.0000 + 0.0000i -1.5000 - 0.8660i

You might also like