You are on page 1of 21

# -: EXPIREMENT # 1:-

INTRODUCTION TO MATLAB
OBJECTIVE:
The objectives of this lab session are to:
(i) Become familiar with MATLAB environment
(ii) Become familiar with Basic MATLAB commands
(iii) Write small programs using MATLAB

BACKGROUND:
MATLAB is a high level computer language used for the programming of
complex engineering problems. MATLAB stands for MATrix LABoratory. As the
name suggests, MATLAB a plethora of functions used for different operations on
matrices, where a matrix can be scalar (single element), a vector (one dimensional) or
an n x m Matrix (two dimensional).

## In MATLAB we have many tool boxes each containing functions related to

specific operations, just as we have libraries in JAVA or C language.
Communications, Control System, Image processing and Image acquisition are some
of the most commonly used tool boxes. MATLAB has extensive capabilities of two
and three dimensional plotting. We will use these plotting facilities of MATLAB to
aid in the physical interpretation of equations, particularly those related to fields and
potentials.
In MATLAB, there are two modes of executing a program; the first one is
command line execution and the second one is M-File or DOT M (.m) file execution.
For command line execution commands are entered in the command window where
(.m) file, complete program is first written in a file and saved with DOT M (.m)
extension. The complete program is then RUN like any other programming language.
We will use DOT M files throughout this lab.

BASIC TERMINOLOGY:
MATLAB has some basic terms and predefined variables you should get
familiar with before going any further. One of these is the variable ans. When you
type most commands to MATLAB, they will return values. You can assign these
values to variables by typing in equations. For example, if you type

>>x = 5

## MATLAB will print

x=
5
And assign the number five to the variable x. MATLAB uses ans for any expression
you don't assign to a variable. For instance, if you type

>> 5
MATLAB will return

ans =

And assign the value 5 to the variable ans. Thus, ans will always be assigned to the
most recently calculated value you didn't assign to anything else.
If you terminate a command with a semi-colon, MATLAB will suppress the
printing of the variable name and value resulting from the calculation. For example, if
you type

>>x = 5;

MATLAB will assign the value five to the variable x, but rather than tell you it did
that, it will just return another << prompt. MATLAB works with two basic types of
data objects: scalars and matrices. MATLAB also has vectors. Vectors are a special
case of matrices which are only 1 row by any number of columns. To assign x to be a
matrix by explicitly entering the elements, you type the list of elements separated by
blanks or commas surrounded by [ and ], and use semi-colons to separate the rows.
For example, typing

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

Results in

x= 2 4 6 8
1 3 5 7

The MATLAB workspace is defined as the collection of all the variables you have
defined during the current MATLAB session.

INDEXING:
At times, you will want to deal with just a part of a vector or matrix. To do
this, you need to use MATLAB's indexing facility. To get the nth element of the
vector x, you type x(n). MATLAB does not use ZERO-BASED indexing (as in
C/C++ or JAVA). MATLAB starts counting from one when numbering vector
elements, so the first element of x is x(1) and not x(0). You can also use indices on
matrices. The element in the row, jth column of x is x(i , j).

>>x = [ 2 4 6 8 ]

## What is the output of following commands?

>>x (1)
>>x (3)
>>x (0)

BASIC ARITHMETIC:
MATLAB uses a straightforward notation for basic arithmetic on scalars. The
symbol + is used to add scalars, so x = 1 + 5 will give x the value 6. Similarly,
MATLAB uses – for subtraction, * for multiplication, / for division, and ^ for
exponentiation. All of these work for two scalars. In addition, you can add, subtract,
multiply or divide all the elements of a vector or matrix by a scalar. For example, if x
is a matrix or vector, then x+1 will add one to each element of x, and x/2 will divide
each element of x by 2. all of the basic operations ( =, -, *, /, and ^) are defined
to work with complex scalars.
Another useful operator is the colon. You can use the colon to specify a range of
numbers. Typing

>>x = 1 : 4

Will return

X=
1 2 3 4

You can optionally use a third number in between the following commands:

>>x = 8 : -1 : 5
>>x = 0 : 0.25 : 1.25

Record the output. What is the function of "-1" and "0.25" in above commands?

MATLAB HELP:
MATLAB has a fairly good help facility. The help function knows about all
the commands listed in this manual. Typing help function will tell you the syntax for
the function, i.e. what arguments it expects. It will also give you a short description
of claims you are in error, try looking at the help for the functions you are using.

>>help plot
>>help for
>>help subplot
>>help roots

## Try the following commands

>>doc plot
>>doc for
>>doc subplot
>>doc roots

What is the difference between help and dot? What do you learn about these

POLYNOMIAL OPERATIONS:
Vectors are used to represent polynomials. If you want to represent an Nth-
order polynomial, you use a length N+1 vector where the elements are the coefficients
of the polynomial arranged in descending order of exponent. So, to define a
polynomial (y = x2 -5x + 6) you would type:

>> y = [1 -5 6] ;

The MATLAB roots function will calculate the roots of a polynomial for you.
Execute the following command

>> roots(y)

Record the output of above command; compare it with the roots of equation
calculated manually.

Try roots command on following polynomials and record your observations:
y = x2 – 4

y = x5 – 3x3 + 7

y = 745x9 – 384x4 + 7

CONTROL STRUCTURES:
MATLAB includes several control structures to allow you to write programs.
The "for" command allows you to make a command or series of commands be
executed several times. It is functionally very similar to the for function in C or java.

FOR-LOOP:

>>for i = 1 : 4
>> i
>>end

Note down the output of above command. From the help find the syntax for "while"
loop, Translate the above program into equivalent while loop and write down your
code:

## You can have nested for loops.

>>for m= 1 : 3
>> for n= 1 : 3
>> x(m,n) = m+n*i;
>>end
>>end

## Record the output of above program, what do you observe?

IF-STATEMENT:
The "if" command lets you have programs that make decisions about what
commands to execute. The basic command looks like

>>a=5;
>>if a>0
>> x=a^2
>>end

This command will assign x to be the value of a squared, if a is positive. Again, note
that it has to have an end to indicate which commands are actually parts of the if. In
addition, you can define an else clause which is executed if the condition you gave the
if is not true. We could expand our example above to be

>>a= -5;
>>if a>0
>> x = a^2
>>else
>> x = -a^2
>>end

## We can also have "if-else if" in MATLAB

>>if a>0
>> x = a^2;
>>else if a = = 0
>> x = i;
>>else
>> x = -a^2
>>end

Try different values of a and note down your observation. Why we are using two end
statements?

Like any other programming language MATLAB also has provision to write
comments. In MATLAB what ever follows % mark in a line is declared as comment

% This is a comment

While doing your homework assignments make sure that you include essential

CONCLUSIONS:
Describe your conclusions based on the objectives of this lab session:
-: EXPERIMENT # 2 :-

MATLAB FUNCTIONS

OBJECTIVE:
The objectives of this lab session are to:
(i) Become familiar with MATLAB Built-in functions
(ii) Become familiar with, how to write USER-DEFINED function in MATLAB
(iii) Write small programs using MATLAB using M-Files.

OVERVIEW:
Function in MATLAB is just like method and routine, in any other language.
Every Tool Box in MATLAB has its own set of functions. In writing a program to
solve a complex problem we usually use a mixture of MATLAB built-in functions
and user-defied functions. We need user-defined functions to address our problem in
particular or to have better and efficient implementation of a complicated algorithm.

BUILT-IN FUNCTIONS:
There are several built-in function in MATLAB, we will explore some of them.

TRIGONOMETRIC FUNCTIONS:
Those known to MATLAB are sin, cos, tan and their arguments should be in radians.

## OTHER ELEMENTARY FUNCTIONS:

These include sqrt, exp, log, log10
Write some commands to use these functions note down the output:

USER-DEFINED FUNCTIONS:
As told earlier, you can write your functions using M-files. There are two
classes of M-files, functions and scripts. An M-file is a function if the first word in it
is a function. A function can just take several arguments or none at all, and return any
number of values. The first line of the file specifies the name of the function, along
with the number and names of input arguments and output values.

## 1) FUNCTIONS RETURNING NO VALUES:

A common example of a function that doesn't return any values is one that
draws graphs. It just draws the graphs, then finishes. Here is an example of such a
function. Save the following program in a file with ".m" file extension.

## Function starts (t)

% STARS (T) draws stars with parameter t
n = t*50;
plot (rand (1,n) , rand (1,n) , 'bx')
% that line plots n random points
title ('My God, Its Full of stars!);
% label the graph

## You can invoke the function by typing:

>>stars (5)

You are unfamiliar with some of the functions in this program; we will discuss them
later on, for the moment check the output and write comments after passing different
arguments to the function.

2) FUNCTIONS RETURNING ONE VALUE
Next, we look at an example of a function that returns one value. Save the
following function in M-file,

if n>0
Y = n^2
else if n = = 0
Y=i
else
Y = -n^2
end
end

## on the command prompt you can invoke the function as:

>>A = 5;
>>B = MY_FUNCTION (A)

## 3) FUNCTIONS RETURNING MORE THAN ONE VALUE

How can we write a function to return more than one value? Find the answer
using MATLAB help. Write a simple function returning three values.

SCRIPT M-FILES
As we mentioned earlier, there is a second kind of M-file. The script type M-
file is just a list of commands to execute in sequence. This differs from a function M-
file in that no arguments are needed. Also, the variables inside a script file are the
same ones as in the main MATLAB workspace. If I have a variable named n = 1000,
than execute a script that includes the line n = 2, my variable will now be 2, and not
1000. To create a script file, just create a file that contains the commands you want
executed. A script file should not have the word function in the first line, and doesn't
need the comments for the help command. The file name should still end in .m
though.

Execute the stars program using a script M-file. What changes did you make?

EXERCISE:

Write down a function factorial (n) which calculates factorial of "n" and returns the

CONCLUSIONS:
Describe your conclusions based on the objectives of this lab session:

HOMEWORK ASSIGNMENT:
You can find the number of seconds it took to execute the instruction or program,
using stopwatch of MATLAB. To start the stopwatch write "tic"' and to stop write
"toc". For example to find the execution time of stars program, you can write

## 1) Write a function displaying first N elements of FIBONACCI series, iteratively.

2) Write another function displaying first N elements of FIBONACCI series,
recursively.
3) Using TIC-TOC command find out which implementation is faster? Why? (use
larger values of N).
-: EXPERIMENT # 3 :-

## BASIC VECTOR AND MATRIX OPERATIONS USING

MATLAB
OBJECTIVE:
The objectives of this lab session are to:
i) Become familiar with the vector representation in MATLAB
ii) Become familiar with the matrix representation in MATLAB
iii) Become familiar with the basic operations on vectors and matrices supported by
MATLAB
iv) Analyze the conversion of different coordinate systems.

OVERVIEW:
In electromagnetics we will encounter some several vectors fields. Thus to
solve electromagnetics problems in MATLAB, we should have sound understanding
of how vectors are represented in MATLAB and what operations are supported in
MATLAB. Also we will discuss two dimensional data structures i.e. matrices. Since
MATLAB is matrix laboratory, it is efficient in performing calculations related to
MATLAB. In fact, we can translate almost all of our problems in MATLAB into
matrix calculations and thus avoiding the conventional FOR or WHILE loops, which
are not recommended in MATLAB.

## EXTRACTING BITS OF A VECTOR:

Run the following command.

>>r = [1 : 2 : 6 , -1 : -2 : -7]
>>r = (3 : 6)
>>r (1 : 2 : 7)
>>r (6 : -2 : 1)

Carefully analyze output of above commands and note down your observations.

TRANSPOSING:
We can convert a row vector into a column vector ( and vice versa ) by a process
called transposing, denoted by ' .
Run the following commands and record output and observations.

>>c=[1 ; 3 ; sqrt(5) ]
>>w=[1 ; -2 ; 3]
>>t=w+2*c'
>>T=5*w'-2*c

Take transpose of
>>x = [1+3i , 2-2i]
i.e.
>>x'
What is output? Why?

## What is the difference from the previous output? Why?

SCALAR PRODUCT:
The scalar produce is defined by multiplying the corresponding elements
together and adding the results to give a single number. Suppose we have the
following vectors:

## >> u= [10 -11 12]

>> v= [20 ; -21 ; -22]
>> w= [2 1 3]

The command for scalar produce is "*". However the vector (or matrix) dimensions
must agree, i.e. 1xn vector can be multiplied with nx1 vector.
Try the following commands and find out output. Write down your comments and
observations.
>> u * v
>> u * w
>> u * w'
>> u * u'

Try ":*" instead of "*". What is the difference between these commands? Dot (A,B) is
another command used to calculate dot produce. Try dot command on some of the
above vectors.

## DOT DIVISION OF ARRAYS/VECTORS:

There is no mathematical definition for the division of one vector by another.
However, in MATLAB, the operator ./ is defined to give element by element division.
It is therefore defined for vectors of same size and type.

## >>a = 1:5, b= 6:10

>>a./b
>>a./a
>>c = -2:2
>>a./c
>>c./c

You will have encountered INF and NAN in the output of above commands. Explain
them:

## DOT POWER OF ARRAYS/VECTORS:

To square each element of a vector we could, for example, do u.*u. however,
a neater way is to use the .^ operator.
Try the following commands:

>> u.^2
>> u.^4
>> u.*w.^(-2)
VECTOR PRODUCT:
Cross (A,B) is the command used to find cross product or vector product of two
vectors. Find cross product (A x B), where A = 3ux + 4uy +5uz and B = 5ux + 4uy +
3uz. Also find B x A.

SIZE OF A MATRIX:
We can find out the size of a matrix by command size.
>> size (A)
>> size (D)
>> size(A')
>> size(D')

SPECIAL MATRICES:
MATLAB provides a number of useful built-in matrices of any desired size.
Try the following matrices and write down function of each of them.
>>P=ones(2,3)
>>Z=zeros(2,3)
>>X=eye(5)

EXTRACTING BITS OF MATRICES:
Following commands are used to extract bits of a matrix. Try each of following
command and write down your observations

## >>J = [1:4 ; 5:8 ; 9:12 ; 20 0 5 4]

>>J(2,3)
>>J(: ,3)
>>J(: ,3:3)
>>J(4, : )
>>J(2:3 , 2:3)

MATRIX PRODUCTS:
The products defined for vectors also work for matrices.
Try the following commands

>>A= [5 7 9 ; 1 -3 -7]
>>B= [-1 2 5 ; 9 0 5]
>>x= [8 ; -4 ; 1]
>>A.*B
>>A*x
>>x*A

Also Try.

>>B= [0 1 ; 3 -2 ; 4 2]
>>C=A*B
>>D=B*A
>>E=B'*A'

CONVERSION OF COORDINATE SYSTEM:

## z = ρcosΦ x = rcosθ x = ρsinΦcosθ

r = ρsinΦ y = rsinθ y = ρsinΦsinθ
z=z z=z z = ρcosΦ

z2 + r2 = ρ2 x2 + y2 = r2 x2 + y2 + z2 = ρ2
tanΦ = r/z tanθ = y/x tanθ = y/x

## Let us convert the Cartesian coordinate system to cylindrical coordinate system.

>>clear
>> p = 1;
>> for i=0:pi/10:2*pi
X(p)=1*cos(i)
p=p+1;
end
>> x=[x;x]
>> p=1;
>> for i=0:pi/10:2*pi
y(p)=1*sin(i)
p=p+1;
end
>> y=[y;y];
>>z=[zeros(1,21);ones(1,21)]

>>surf(x,y,z)