You are on page 1of 76

INTRuDUCTIuN Tu MATLAB

uB)ECTIVE: The objectives oI this lab session are to:


(i) Become Iamiliar with MATLAB environment
(ii) Become Iamiliar with Basic MATLAB commands
(iii) Write small programs using MATLAB
BACKCRuUND:
MATLAB is a high level computer language used Ior the programming oI
complex engineering problems. MATLAB stands Ior MATrix LABoratory. As the name
suggests, MATLAB a plethora oI Iunctions used Ior diIIerent 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 Iunctions related to speciIic
operations, just as we have libraries in JAVA or C language. Communications, Control
System, Image processing and Image acquisition are some oI the most commonly used tool
boxes. MATLAB has extensive capabilities oI two and three dimensional plotting. We will use
these plotting Iacilities oI MATLAB to aid in the physical interpretation oI equations,
particularly those related to Iields and potentials.
In MATLAB, there are two modes oI executing a program; the Iirst one is
command line execution and the second one is M-File or DOT M (.m) Iile execution. Eor
command line execution commands are entered in the command window where (.m) Iile,
complete program is Iirst written in a Iile and saved with DOT M (.m) extension. The
complete program is then RUN like any other programming language. We will use DOT M
Iiles throughout this lab.
BASIC TERMINuLuCY:
MATLAB has some basic terms and predeIined variables you should get Iamiliar
with beIore going any Iurther. One oI 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. Eor example, iI you type
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:00
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
~~x 5
MATLAB will print
x
5
And assign the number Iive to the variable x. MATLAB uses ans Ior any expression you
don't assign to a variable. Eor instance, iI you type
~~ 5
MATLAB will return
ans 5
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.
II you terminate a command with a semi-colon, MATLAB will suppress the
printing oI the variable name and value resulting Irom the calculation. Eor example, iI
you type
~~x 5;
MATLAB will assign the value Iive to the variable x, but rather than tell you it did that, it
will just return another << prompt. MATLAB works with two basic types oI data objects:
scalars and matrices. MATLAB also has vectors. Vectors are a special case oI
matrices which are only 1 row by any number oI columns. To assign x to be a matrix by
explicitly entering the elements, you type the list oI elements separated by blanks or
commas surrounded by and ], and use semi-colons to separate the rows. Eor 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 deIined as the collection oI all the variables you have
deIined during the current MATLAB session.
INDEXINC:
At times, you will want to deal with just a part oI a vector or matrix. To do this,
you need to use MATLAB's indexing Iacility. To get the nth element oI the vector x, you
type x(n). MATLAB does not use ZERO-BASED indexing (as in C/C or JAVA).
MATLAB starts counting Irom one when numbering vector elements, so the Iirst element
oI x is x(1) and not x(0). You can also use indices on matrices. The element in the row,
fth column oI x is x(i , f).
~~x | 2 4 6 8 |
What is the output oI Iollowing commands?
~~x (1)
~~x (3)
~~x (0)
uUTPUT & CuMMENTS:
BASIC ARITHMETIC:
MATLAB uses a straightIorward notation Ior basic arithmetic on scalars. The
symbol + is used to add scalars, so x 1 5 will give x the value 6. Similarly, MATLAB
uses - Ior subtraction, ` Ior multiplication, / Ior division, and ^ Ior exponentiation. All oI
these work Ior two scalars. In addition, you can add, subtract, multiply or divide all the
elements oI a vector or matrix by a scalar. Eor example, iI x is a matrix or vector, then
x1 will add one to each element oI x, and x/2 will divide each element oI x by 2. all oI
the basic operations ( , -, `, /, and ^) are deIined to work with complex scalars.
Another useIul operator is the colon. You can use the colon to speciIy 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 Iollowing commands:
~~x 8 : -1 : 5
~~x 0 : 0.25 : 1.25
Record the output. What is the Iunction oI "-1" and "0.25" in above commands?
Num denotes the numerator, iI given equation have numerator as well as
denumerator.
Den denotes the denumerator
These are commands Ior numerator and denumerator..
uUTPUT AND CuMMENTS:
MATLAB HELP:
MATLAB has a Iairly good help Iacility. The help Iunction knows about all
tcommands listed in this manual. Typing help Iunction will tell you the syntax Ior the
Iunction, i.e. what arguments it expects. It will also give you a short description oI
claims you are in error, try looking at the help Ior the Iunctions you are using.
Check MATLAB help Ior PLOT, FOR, SUBPLOT, ROOTS.
~~help plot
~~help Ior
~~help subplot
~~help roots
Try the Iollowing commands
~~doc plot
~~doc Ior
~~doc subplot
~~doc roots
What is the diIIerence between help and dot? What do you learn about these commands?
Record your observation:
uUTPUT & CuMMENTS:
PuLYNuMIAL uPERATIuNS:
Vectors are used to represent polynomials. II you want to represent an Nth-order
polynomial, you use a length N1 vector where the elements are the coeIIicients oI the
polynomial arranged in descending order oI exponent. So, to deIine a polynomial (y x
2
-5x 6) you would type:
~~ y |1 -5 6| ;
The MATLAB roots Iunction will calculate the roots oI a polynomial Ior you. Execute
the Iollowing command
~~ roots(y)
Record the output oI above command; compare it with the roots oI equation calculated
manually.
uUTPUT & CuMMENTS:
Try roots command on Iollowing polynomials and record your observations:
y x
2
4
uUTPUT & CuMMENTS:
y x
5
4x
4
3x
3
6
uUTPUT & CuMMENTS:
y 745x
9
384x
4
7
uUTPUT & CuMMENTS:
CuNTRuL STRUCTURES:
MATLAB includes several control structures to allow you to write programs.
"for" command allows you to make a command or series oI commands be executed
several times. It is Iunctionally very similar to the for Iunction in C or java.
FuR-LuuP:
~~Ior i 1 : 5
~~ i
~~end
Note down the output oI above command. Erom the help Iind the syntax Ior "while"
loop, Translate the above program into equivalent while loop and write down your code:
uUTPUT & CuMMENTS:
You can have nested for loops.
~~Ior m 1 : 3
~~ Ior n 1 : 3
~~ x(m,n) mn*i
~~end
~~end
Record the output oI above program, what do you observe?
uUTPUT & CuMMENTS:
IF-STATEMENT:
The "if" command lets you have programs that make decisions about what
commands to execute. The basic command looks like
~~a5;
~~iI a~0
~~ xa`2
~~end
This command will assign x to be the value oI a squared, iI a is positive. Again, note that
it has to have an end to indicate which commands are actually parts oI the if. In addition,
you can deIine an else clause which is executed iI the condition you gave the if is not
true. We could expand our example above to be
~~a -5;
~~iI a~0
~~ x a`2
~~else
~~ x -a`2
~~end
Try diIIerent values oI a and note down your observation.
uUTPUT & CuMMENTS:
We can also have "if-else if" in MATLAB
~~iI a~0
~~ x a`2
~~else iI a 0
~~ x i
~~else
~~ x -a`2
~~end
Try diIIerent values oI a and note down your observation. Why we are using two end
statements?
uUTPUT & CuMMENTS:
CuMMENTS:
Like any other programming language MATLAB also has provision to write
comments. In MATLAB what ever Iollows mark in a line is declared as comment
This is a comment
While doing your homework assignments make sure that you include essential comments
to elaborate your program.
CuNCLUSIuNS:
Describe your conclusions based on the objectives oI this lab session:
Conversion of point and vector between the
coordinate systems:
uB)ECTIVE:
The objectives oI this lab session are to:
(i) How to Convert a point between the coordinate systems
(ii) Be Iamiliar with built in Iunctions related to coordinate systems conversion
THEuRY:
Coordinate system is mathematical tools with which the concepts oI electromagnetic Iield are
explained. Our concern in EMET is the charge densities Ior example point charge and sheet oI
charge. These charge densities are well explained and analyzed with the help oI coordinate
system, Ior instance, in the case oI point charge the preIerred coordinate system will be spherical
because oI symmetry, Ior line charge we consider cylindrical coordinate system and Ior sheet oI
charge the Cartesian coordinate system is used Ior analysis.
In Cartesian system the coordinate point are (x, y, z) with limits Irom- to each . Here x, y, z
represents the planes oI inIinite extent. In cylindrical system the coordinate point are (p , ,z) . p
describes the radius oI cylinder Irom 0 to , describes the plane with limits Irom 0 to 2a and
z describes the another plane with limits Irom -to . In spherical system the coordinate point
are (r,0 , ) , r represents radius oI sphere with limits 0 to , 0 describes the cone with limits 0 to
a and describes the plane with limits 0 to 2a .
Now it is Irequently required to convert a point Irom one coordinate system to other, Ior which
the Iollowing equations are used.
So a point in cylindrical system can be converted into Cartesian
system. Similarly,
These equations are used to transIorm a point Irom Cartesian system to cylindrical system.
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory
Electrical Engineering {4
th
LAB EXPERIMENT:01
NO:01
Name: Roll No:
Lab Instructor Signature: Date:
Eor converting a point Irom Cartesian to spherical system, we used the Iollowing Equations:
And Ior converting Irom spherical to Cartesian system we use
TransIorming Irom Cartesian to Cylindrical System:
Let a vector is given in Cartesian system,
Now it is required to transIorm it into cylindrical system i:e
So, the values oI Ap ,AO and Az will be required. Eor which we Iollow the procedure as given
below.
To Iind 'Ap we take dot product between A (Cartesian) and unit vector ap (which is oI desired
direction).
Similarly to Iind 'AO we take dot product between A( Cartesian) and unit vector aO.
Similarly to Iind 'Az
So as we see Irom equations( 3) to (5) that there is dot product between unit
vector oI dissimilar coordinates system which are summarized in tabular Iorm as under
Cylindrical- Spherical Cylindrical-Rectangular Spherical-Rectangular
z pcos4
r psin4
z z
x rcos0
y rsin0
z z
x psin4cos0
y psin4sin0
z pcos4
z
2
r
2
p
2
tan4 r/z
x
2
y
2
r
2
tan0 y/x
x
2
y
2
z
2
p
2
tan0 y/x
Let us convert the Cartesian coordinate system to cylindrical coordinate system:
clear
p 1;
Ior i0:pi/10:2*pi
X(p)1*cos(i)
pp1;
end
x|x;x|
p1;
Ior i0:pi/10:2*pi
y(p)1*sin(i)
pp1;
end
y|y;y|;
z|zeros(1,21);ones(1,21)|
surI(x,y,z)
uUTPUT & CuMMENTS:
HuMEWuRK ASSICNMENT:
Write down a program which (veriIy results using MATLAB built-in Iunctions):
Write down a program oI Iollowing using MATLAB built-in Iunction):
TransIorm Cartesian coordinates to spherical
TransIorm Polar oI Cylindrical coordinates to Cartesian
TransIorm Spherical coordinates to Polar or Cylindrical
TransIorm Cylindrical coordinates to Spherical
MATLAB FUNCTIuNS
uB)ECTIVE:
The objectives oI this lab session are to:
(i) Become Iamiliar with MATLAB Built-in Iunctions
(ii) Become Iamiliar with, how to write USER-DEFINED Iunction in MATLAB
(iii) Write small programs using MATLAB using M-Files.
uVERVIEW:
Eunction in MATLAB is just like method and routine, in any other language.
Every Tool Box in MATLAB has its own set oI Iunctions. In writing a program to solve a
complex problem we usually use a mixture oI MATLAB built-in Iunctions and user- deIied
Iunctions. We need user-deIined Iunctions to address our problem in particular or to have
better and eIIicient implementation oI a complicated algorithm.
BUILT-IN FUNCTIuNS:
There are several built-in Iunction in MATLAB, we will explore some oI them.
TRICuNuMETRIC FUNCTIuNS:
Those known to MATLAB are sin, cos, tan and their arguments should be in radians.
~~x 5*cos(pi/6) , y 5*sin(pi/6)
What are the commands Ior sin
-1
, cos
-1
, and tan
-1
?
uUTPUT & CuMMENTS:
Note that in MATLAB we have predeIined value PI in the constant pi.
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Tbeory
Electrical Engineering {4
tb
LAB EXPERIMENT:02
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
2) FUNCTIONS RETURNING ONE
Next, we look at an example oI a Iunction that returns one value. Save the
Iollowing Iunction in
uTHER ELEMENTARY FUNCTIuNS:
These include sqrt, exp, log, log10
Write some commands to use these Iunctions note down the output.
uUTPUT & CuMMENTS:
USER-DEFINED FUNCTIuNS:
As told earlier, you can write your Iunctions using M-files. There are two classes
oI M-files, Iunctions and scripts. An M-file is a Iunction iI the Iirst word in it is a
Iunction. A Iunction can just take several arguments or none at all, and return any
number oI values. The Iirst line oI the Iile speciIies the name oI the Iunction, along with
the number and names oI input arguments and output values.
1] FUNCTIuNS RETURNINC Nu VALUES:
A common example oI a Iunction that doesn't return any values is one that draws
graphs. It just draws the graphs, then Iinishes. Here is an example oI such a Iunction.
Save the Iollowing program in a Iile with ".m" Iile extension.
Iunction stars (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 Eull oI stars!);
label the graph
You can invoke the Iunction by typing:
~~stars (5)
You are unIamiliar with some oI the Iunctions in this program; we will discuss them later
on, Ior the moment check the output and write comments aIter passing diIIerent arguments
to the Iunction.
uUTPUT & CuMMENTS:
OUTPUT &
Iunction MYEUNCTION (n)
iI n~0
Y n`2
else iI n 0
Y i
else
end
Y -n`2
end
on the command prompt you can invoke the Iunction as:
~~A 5;
~~B MYEUNCTION (A)
Record the output oI above program, try diIIerent values oI A.
uUTPUT & CuMMENTS:
3] FUNCTIuNS RETURNINC MuRE THAN uNE VALUE
How can we write a Iunction to return more than one value? Eind the answer
using MATLAB help. Write a simple Iunction returning three values.
SCRIPT M-FILES:
As we mentioned earlier, there is a second kind oI M-file. The script type M-file
is just a list oI commands to execute in sequence. This diIIers Irom a Iunction M-Iile in
that no arguments are needed. Also, the variables inside a script Iile are the same ones as in
the main MATLAB workspace. II 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 Iile,
just create a Iile that contains the commands you want executed. A script Iile should not
have the word Iunction in the Iirst line, and doesn't need the comments Ior the help
command. The Iile name should still end in .m though.
Execute the stars program using a script M-file. What changes did you make?
uUTPUT & CuMMENTS:
EXERCISE:
Write down a Iunction factorial (n) which calculates Iactorial oI "n" and returns the
value. Test your program.
uUTPUT & CuMMENTS:
CuNCLUSIuNS:
Describe your conclusions based on the objectives oI this lab session:
HuMEWuRK ASSICNMENT:
You can Iind the number oI seconds it took to execute the instruction or program, using
stopwatch oI MATLAB. To start the stopwatch write "tic"' and to stop write "toc". Eor
example to Iind the execution time oI stars program, you can write
~~ tic, stars(5) ,toc
1) Write a Iunction displaying Iirst N elements oI FIBONACCI series, iteratively.
2) Write another Iunction displaying Iirst N elements oI FIBONACCI series,
recursively.
3) Using TIC-TOC command Iind out which implementation is Iaster? Why? (use larger
values oI N).
BASIC VECTuR AND MATRIX uPERATIuNS USINC
MATLAB
uB)ECTIVE:
The objectives oI this lab session are to:
i) Become Iamiliar with the vector representation in MATLAB
ii) Become Iamiliar with the matrix representation in MATLAB
iii) Become Iamiliar with the basic operations on vectors and matrices supported
by MATLAB
iv) Analyze the conversion oI diIIerent coordinate systems.
uVERVIEW:
In electromagnetics we will encounter some several vectors Iields. Thus to solve
electromagnetics problems in MATLAB, we should have sound understanding oI 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 eIIicient in perIorming calculations related to MATLAB. In Iact,
we can translate almost all oI our problems in MATLAB into matrix calculations and
thus avoiding the conventional EOR or WHILE loops, which are not recommended in
MATLAB.
EXTRACTINC BITS uF A VECTuR:
Run the Iollowing command.
r |1 : 2 : 6 , -1 : -2 : -7|
r (3 : 6)
r (1 : 1 : 4)
r (6 : -2 : 1)
CareIully analyze output oI above commands and note down your observations.
uUTPUT & CuMMENTS:
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:03
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
TRANSPuSINC:
We can convert a row vector into a column vector ( and vice versa ) by a process called
transposing, denoted by ' .
Run the Iollowing commands and record output and observations.
c|1 ; 3 ; sqrt(5) |
c|2 3 6 ; 4 6 7; 4 8 9|
uUTPUT & CuMMENTS:
Take transpose oI
x |13i , 2-2i|
i.e.
x'
What is output? Why?
uUTPUT & CuMMENTS:
SCALAR PRuDUCT:
The scalar produce is deIined by multiplying the corresponding elements together
and adding the results to give a single number. Suppose we have the Iollowing vectors:
u |8 -11 10|
v |10 ; -21 ; -52|
w |2 1 3|
The command Ior scalar produce is "`". However the vector (or matrix) dimensions
must agree, i.e. vector can be multiplied with vector.
Try the Iollowing commands and Iind out output. Write down your comments and
observations.
u * v
u * w
u * w'
u * u'
Try ":*" instead oI "*". What is the diIIerence between these commands? Dot (A,B) is
another command used to calculate dot produce. Try dot command on some oI the above
vectors.
uUTPUT & CuMMENTS:
Now iI
u|2 4 6; 4 6 -8;-1 5 8|
v|-3 5 6; 3 6 8;0 2 5|
w|2 -5 7; 2 5 9;-3 4 6|
then Iind out the values oI
u * v and u/v
u * w and w/u
u * w' and u/w
uUTPUT & CuMMENTS:
DuT DIVISIuN uF ARRAYSJVECTuRS:
There is no mathematical deIinition Ior the division oI one vector by another.
However, in MATLAB, the operator ./ is deIined to give element by element division. It
is thereIore deIined Ior vectors oI same size and type.
a 1:5, b 6:10
a./b
a./a
c -2:2
a./c
c./c
uUTPUT & CuMMENTS:
SIZE OF A MATRIX:
We can Iind out the size oI a matrix by command size.
You will have encountered INF and NAN in the output oI above commands. Explain
them:
uUTPUT & CuMMENTS:
DuT PuWER uF ARRAYSJVECTuRS:
To square each element oI a vector we could, Ior example, do u.`u. however, a
neater way is to use the .^ operator.
Try the Iollowing commands:
~~ u.`2
~~ u.`4
~~ u.*w.`(-2)
uUTPUT & CuMMENTS:
VECTuR PRuDUCT:
Cross (A,B) is the command used to Iind cross product or vector product oI two vectors.
Eind cross product (A x B), where A 3a
x
4a
y
-65a
z
and
B 3a
x
-7 4a
y
3a
z
. Also Iind B x A.
uUTPUT & CuMMENTS:
EXTRACTING BITS OF MATRICES:
Eollowing commands are used to extract bits oI a matrix. Try each oI Iollowing
size (A)
size (D)
size (A')
size (D')
uUTPUT & CuMMENTS:
SPECIAL MATRICES:
MATLAB provides a number oI useIul built-in matrices oI any desired size.
Try the Iollowing matrices and write down Iunction oI each oI them.
Pones(2,3)
Zzeros(2,3)
Xeye(5)
uUTPUT & CuMMENTS:
command and write down your observations
J |1:4 ; 5:8 ; 9:12 ; 20 0 5 4|
J(2,3)
J(: ,3)
J(: ,3:4)
J(4, : )
J(1, : )
J(2:3 , 2:3)
J(2:3 , 3:4)
uUTPUT & CuMMENTS:
MATRIX PRuDUCTS:
The products deIined Ior vectors also work Ior matrices.
Try the Iollowing 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|
CA*B
DB*A
EB'*A'
uUTPUT & CuMMENTS:
BASIC CRAPHIC TuuLS IN MATLAB
uB)ECTIVE:-
The objectives oI this lab session are to:
i) Become Iamiliar with the basic graphic tools in MATLAB
ii) Become Iamiliar with the procedure to draw and label 2-d graphs
iii) Become Iamiliar with the procedure to draw 3-D Iigures.
uVERVIEW:
In addition to the mathematical operations discussed in earlier experiments, MATLAB
provides extensive two and three dimensional graphical plotting routines. The data to be plotted can
be generated internally in a program or it can be imported Irom an external program. Labels and
titles using diIIerent Ionts and Iont sizes and styles can be placed on the graphs and the plots can be
distinguished with diIIerent symbols. We will start Irom very basic plotting commands and
progressively move towards sophisticated commands.
PLuT:
PLOT is the basic command used to draw two dimensional graphs. Suppose we wish to plot a
graph between one set oI numbers versus another set oI numbers you will type plot (X,Y) where X
contain x-axis values and Y contains Y-axis values
~~a |2 4 5 8 10|;
~~b |5 4 3 2 1|;
~~plot(plot(a,b,`*`);
~~xlabel(a`);
~~ylabel(b`);
~~title ((b) Plot oI two numbers`);
where, xlabel & ylabel commands are used to add labels to x and y axis respectively. Similarly,
title is used to add title to the plot.
Now, Irom the help oI MATLAB Iind out all other options available with the PLOT
command. Can you Iind out what is the Iunction oI `` in above mentioned command. What are
alternatives to ` that we can use in plot? Remove * Irom plot, what is the diIIerence Irom
previous plot? How we can change the color oI plot?
Note: Multiple commands can be given on a single line using , ]
CRID:
A dotted grid may be added to a plot by
~~grid
this can be removed using either grid again, or grid off. HOLD:
A call to plot clears the graphics window beIore plotting the current graph. This is
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:04
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
not convenient iI we wish to add Iurther graphics to Iigure at some later stage. To stop the
window Irom being cleared:
~~x1 : 0.1 : 10, ysin(x)
~~plot(x,y), hold
~~plot(x,y,`k*`), hold oII
SUBPLuT:
The graphics window may be split into an m x n array oI smaller windows which we may plot one
or more graphs. The windows are counted 1 to mn row-wise, starting Iorm the top leIt. Both hold
and grid work on the current subplot.
~~x0 : 0.01 : 1; , ysin(3*pi*x);
~~subplot(221) , plot (x,y)
~~ xlabel(x`) , ylabel(sin 3 pi x`)
~~subplot(222) , plot(x,cos(3*pi*x))
~~ xlabel(x`) , ylabel (cos 3 pi x`)
~~subplot(223) , plot(x,sin(6*pi*x))
~~ xlabel(x`) , ylabel (sin 6 pi x`)
~~subplot(224) , plot(x,cos(6*pi*x))
~~ xlabel(x`) , ylabel(cos 6 pi x`)
subplot(221) or subplot(2,2,1) speciIies that the window should be split into a 2 x 2 array and
we select the Iirst subwindow. Similarly, subplot((222) selects the second window the 2 x 2
array oI windows. Take MATLAB help on subplot and note down the important inIormation.
Write down, comments based on above program.
uUTPUT &CuMMENTS:
Subplot(abc) indicates a subplot in a row b column and plot number c. Instead oI
writing plot(x,y) We can also write values oI respective Iunctions
CuNTRuLLINCAXIS:
Once a plot has been created in the graphics window you may wish to change
the range oI x and y values shown on the picture.
~~clI
~~n100; h1/N; x0 : h : 1:
~~ysin(3*pi*x)
~~plot(x,y)
~~axis(|-0.5 1.5 -1.2 1.2|)
~~grid
uUTPUT &CuMMENTS:
Axis(|a s d I|) indicates scale Irom a to s on x axis and d to I on y axis.
EXERCISE 4.1:
Draw graphs oI the Iunctions
Ycosx
Yx Ior 0 _ x _ on the same window. Use the zoom Iacility to determine the point oI
intersection oI the two curves (and hence, the root oI xcosx) to two signiIicant Iigures.
uUTPUT &CuMMENTS:
EXERCISE 4.2:
Draw the graphs oI the Iollowing Iunctions in same window (USE SUBPLOT):
i) y (sinx)/x ii) u 1/(x-1)
2
x
iii) y (x
2
1) / (x
2
4) iv) w (10-x)
1/3
- 2 / (0.4x
2
)
1/2
For 0 x 10
uUTPUT &CuMMENTS:
PLuTTINC SURFACES:
A surIace is deIined mathematically by a Iunction (x,y) corresponding to each value oI
(x,y) we compute the height oI the Iunction by
Z(x,y)
In order to plot this we have to decide on the ranges oI x and y, suppose 2 x 4
and 1 y 3. This gives us a square in the x-y plane. Next, we need to choose
a grid on this domain; figure 1 shows the grid with intervals .2 in each
direction.
Einally, we have to evaluate the Iunction at each point oI the grid and plot it. Suppose
we choose a grid with intervals 0.5 in each direction Ior illustration, the x- and y-
coordinates oI the grid lines are
X0:0.5:4 ; Y1:0.5:3;
in MATLAB notation. We construct the grid with meshgrid
~~|X,Y| meshgrid(2:0.5:4 , :1:0.5:3);
~~X
X
2.0000 2.5000 3.5000 4.0000
2.0000 2.5000 3.5000 4.0000
2.0000 2.5000 3.5000 4.0000
2.0000 2.5000 3.5000 4.0000
2.0000 2.5000 3.5000 4.0000
Y
1.0000 1.0000 1.0000 1.0000
1.5000 1.5000 1.5000 1.5000
2.0000 2.0000 2.0000 2.0000
2.5000 2.5000 2.5000 2.5000
3.0000 3.0000 3.0000 3.0000
iI we think oI the ith point along Irom the leIt and jth point up Irom the bottom oI the
grid as corresponding to the (i,j)th entry in a matrix, then (X(i,j) , Y(i,j)) are the
coordinates oI the point. We then need to evaluate the Iunction ] using X and Y in
place oI x and y, respectively.
Einally the surIace is plotted using mesh(X,Y,Z) command where ZE(X,Y).
~~ZX . `3 Y .`3
~~ mesh(X,Y,Z)
uUTPUT &CuMMENTS:
EXERCISE 4.4:
1) Plot the surIace deIined by the Iunction
(x,y) -xy
-2(x^2+y^2)
on the domain -2 x 2 , -2 y 2
2) Run the command contour(X,Y,Z) & meshc(X,Y,Z) . What do these plot?
3) Eind the values and locations oI the maxima and minima oI the Iunction.(use
max and min commands). Use MATLAB help wherever necessary.
uUTPUT &CuMMENTS:
CuNCLUSIuNS:
Describe your conclusion based on the objectives oI this lab session:
HuMEWuRKASSICNMENT:
Write a program to convert degrees C to degrees F. plot the results.
Plot yexp(-x) on a linear and semilog graph.
Plot two cycles oI ycos(x) on a linear and a polar graph.
Plot y(x) exp(-x) on a linear graph Ior -3 x 3
Plot y(x) exp(-x) on a linear graph Ior -3 x 3. Add the plot oI yx
2
with
a diIIerent linestyle to this graph
Tu PLuT ELECTRIC FIELD AND PuTENTIAL FuR
DIFFERENT CHARCE ARRANCEMENTS
uB)ECTIVE:
When you have completed this experiment you should:
i) Know how to plot electric Iield Ior a given charge arrangement.
ii) Know how to plot electric potential Ior a given charge arrangement.
iii) Be Iamiliar with gradient operation in MATLAB.
uVERVIEW:
The electric Iield caused by a charge Q is a vector quantity and is deIined as
EF/q (Newton`s/Coulomb`s)
Where E is the coulomb Iorce between the two charges Q and q. the standard
symbol Ior the electric Iield is E. the electric Iield in this region due to charge Q is
thereIore written as:
E Q/ 4aC
0
r
2
a
r
Direction oI the electric Iield depends upon the sign oI the charge. We can Iind the Iorce on
a charged particle that is brought into a region containing an electric Iield E by multiplying
the electric Iield by the charge q, that is FqE.
SUPERPuSITIuN PRINCIPLES:
II we had more than one charge and each charge were at a diIIerent location in our
evacuated space, the total electric Iield in the space external to the location oI these charges
would be the vector summation oI the electric Iield originating Iorm each charge. Vacuum is
a linear media, in Iact, a vacuum has the greatest number oI linear properties oI any media.
The introduction oI a material may cause the region to become nonlinear. Linear
superposition applies and the only thing oI which we have to be careIul that we
use a vector superposition instead oI just adding scalar quantities. Both the magnitude and
the direction oI the individual electric Iields must be included in the addition. Eor N
separate charges in the region oI interest, this summation can be written as:
EE
1
+ E
2
+ E
3
+ E
4
+ ... E
N
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:05
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
ELECTRIC PuTENTIAL:
Electric Iield is deIined to be in the direction oI the maximum rate oI change oI
the potential. Hence the electric Iield can be Iound analytically by taking the gradient iI an
electric potential that is,
E -AV
Where, V is deIined to be
V Q / 4aC
0
R
The principal oI superposition is also applicable on electric potential.
EQUIPuTENTIAL SURFACES:
A surIace that has the same potential is called an equipotential surIace. Note that
the amount oI work done to move a unit charge around on an equipotential surIace is
equal to zero.
EXERCISE 5.1:
Eind the potential V Iar Irom two charges oI the opposite sign that are separated
by a distance d. This conIiguration is known as electric dipole. Using MATLAB, sketch the
equipotential contours and the electric Iield surrounding the charges. This model also serves
as sample model Ior an atom
SuLUTIuN:
Assume that the two charges are located at (x
1
,y
1
)(0.25) and (x
2
,y
2
)(0.25). The
potential at a distance r Irom the centre oI the dipole structure can be computed using the
principle oI superposition it is given by:
V Q
1
/ 4aC
0
R
1
- Q
2
/ 4aC
0
R
2
CuNTuUR:
The MATLAB command used to draw equipotential contours Ior potential is
contour (J). Use MATLAB help and note down what you can learn about the contour
command.
uUTPUT & CuMMENTS:
CRADIENT:
In order to Iind electric Iield Irom the potential we need to Iind the gradient oI
electric potential. The MATLAB command Ior gradient is gradient. Use MATLAB help
and note down what you can learn about the gradient command.
uUTPUT & CuMMENTS:
QUIVER:
Einally, to plot the electric Iield vector data which we calculated using gradient
command, is plotted in the Iorm oI arrow vectors using quiver command. Use MATLAB
help and note down what you can learn about the quiver command.
uUTPUT & CuMMENTS:
MATLAB PRuCRAM:
The MATLAB code to solve the above problem is given below. Save the code in
a script m-file and answer the Iollowing questions.
clear; clI
|x , y| meshgrid(-1 : 0.1 : 1)
R1 (x. `2 (y - 0.25). `2). `0.5;
R2 (x. `2 (y 0.25). `2). `0.5;
V1./R1 - 1./R2
subplot(1 , 2 , 1);
surI(x , y ,V)
xlabel(X`)
ylabel(Y`)
zlabel(Z`)
subplot(1 , 2 , 2);
|px , py| gradient(V , 0.1 , 0.1);
contour(V)
hold on
quiver(-px , -py)
hold oII
xlabel(X`)
ylabel(Y`)
uUTPUT & CuMMENTS:
EXERCISE 5.2:
Change the above program to observe the electric Iield and potential iI both
charges are not equal i.e. iI [ Q
1
[ [ 2Q
2
[ & [ Q
1
[ [ 10Q
2
[ also iI [ Q
2
[ [ 2Q
1
[ &
[ Q
2
[ [ 10Q
1
[ . What changes will you make in the code?
uUTPUT & CuMMENTS:
EXERCISE 5.3:
Increase and decrease the distance between the two charges and note down your
observations.
uUTPUT & CuMMENTS:
EXERCISE 5.4:
Repeat exercises 1, 2 and 3 iI both the charges have same polarity.
uUTPUT & CuMMENTS:
CuNCLUSIuNS:
Describe your conclusions based on the objectives oI this lab session:
HuMEWuRK ASSICNMENT:
II another point charge(ive & -ive) is placed in the vicinity oI above
conIiguration, what eIIect does it produce on the electric Iield and potential?
(HINT: Place new charge at diIIerent locations oI original conIiguration and explore as
many possibilities as you can)
How can we perIorm the analysis on 3-D charge distribution? Illustrate with an
example.
S
Simulation of time varying scalar and vector functions
using MATLAB.
Theory:
Those Iunctions that vary with respect to time are called time varying Iunctions and are broadly
classiIied into Iollowing groups:
Time varying scalar functions:
A Iunction that require only magnitude Ior its complete description is called a scalar Iunction, iI
a scalar Iunction undergo change in its magnitude w.r.t time, then it is called time varying scalar
Iunction
Eor example speed oI an accelerating car and temperature oI certain city changes with time, so
these are scalar Iunctions.
Time Varying Vector Function:
A Iunction that require direction as well as magnitude Ior its complete description is known as
vector Iunction and it is called time varying vector Iunction iI it varies w.r.t. to time (in terms oI
either magnitude, direction or both) .
Eor example velocity oI an accelerating car and Iorce on a charge due to alternating magnetic
Iields in its surrounding are both examples oI time varying vectors.
Time Harmonic Vector Function:
II a vector Iunction varies with time such that it attains initial values oI magnitude and direction
aIter a deIinite interval oI time (period) then its known as time harmonic vector Iunction.
The position-vector oI a geosynchronous satellite is a time harmonic vector.
MATLAB is useIul Ior plotting and simulating time varying Iunctions
Eollowing are some MATLAB Iunctions that are essential in simulating time varying Iunctions.
The 'movie' Function:
You can save any sequence oI graphs and then play the sequence back in a short movie. There
are two steps to this process: Use getIrame to generate each movie Irame. Use movie to run the
movie a speciIied number oI times at the speciIied rate. Typically, you use getIrame in a Ior
loop to assemble the array oI movie Irames
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:06
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
Syntax And Description:
Movie plays the movie deIined by a matrix whose columns are movie Irames (usually
produced by getIrame).
movie(M) plays the movie in matrix M once.
movie(M,n) plays the movie n times. II n is negative, each cycle is shown Iorward then
backward. II n is a vector, the Iirst element is the number oI times to play the
movie, and the remaining elements make up a list oI Irames to play in the
movie. Eor example, iI M has Iour Irames then n |10 4 4 2 1| plays the movie
ten times, and the movie consists oI Irame 4 Iollowed by Irame 4 again,
Iollowed by Irame 2 and Iinally Irame 1.
movie(M,n,fps) plays the movie at Ips Irames per second. The deIault is 12 Irames per second.
Computers that cannot achieve the speciIied speed play as Iast as possible.
The movie Iunction displays each Irame as it loads the data into memory, and then plays the
movie. This eliminates long delays with a blank screen when you load a memory-intensive
movie. The movie's load cycle is not considered one oI the movie repetitions.
Example
The 'getframe' Function:
getIrame returns a movie Irame. The Irame is a snapshot (pixmap) oI the current axes or Iigure.
Syntax And Description
E getIrame gets a Irame Irom the current axes.
Usually, getIrame is used in a Ior loop to assemble an array oI movie Irames Ior playback
using movie. Eor example,
In this example n` corresponds to number oI Irames
The 'axis' Function
This Iunction manipulates axis scaling and appearance.
Syntax And Description:
axis([xmin xmax vmin vmax]) sets the limits Ior the x- and y-axis oI the
current axes.
axis([xmin xmax vmin vmax :min :max]) sets the limits Ior the x-,y- and z-axis oI the
current axes
axis([xmin xmax vmin vmax :min :max cmin
cmax])
sets the x-, y-, and z-axis limits and the color
scaling limits) oI the current axes.
Example:
Above code will generate Iollowing axis scaling Iigure
The 'plot3' Function:
The plot3 Iunction displays a three-dimensional plot oI a set oI data points.
Syntax And Description:
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 oI X1, Y1, and Z1.
plot3(X1,Y1,Z1,LineSpec,...) creates and displays all lines deIined by the Xn,Yn,Zn,LineSpec
quads, where LineSpec is a line speciIication that determines
line style, marker symbol, and color oI the plotted lines.
Examples:
The 'quiver3' Function:
A three-dimensional quiver plot displays vectors with components (u,v,w) at the points
(x,y,z) whereas a quiver plot displays velocity vectors as arrows with components (u,v) at
the points (x,y). Eor example, the Iirst vector is deIined by components u(1),v(1) and is
displayed at the point x(1),y(1).
quiver3(x,v,:,u,v,w) plots vectors with components (u,v,w) at the points (x,y,z). The
matrices x,y,z,u,v,w must all be the same size and contain the
corresponding position and vector components.
quiver3(x,v,:,u,v,w,scale) automatically scales the vectors to prevent them Irom overlapping,
then multiplies them by scale. scale 2 doubles their relative length
and scale 0.5 halves them. Use scale 0 to plot the vectors
without the automatic scaling.
Example:
Iig
ure` creates Iigure graphics objects. Eigure objects are the individual windows on the screen in
which MATLAB displays graphical output.
Eigure Windows Graphing Iunctions automatically open a new Iigure window iI there are no
Iigure windows already on the screen. II a Iigure window exists, MATLAB uses that window Ior
graphics output. II there are multiple Iigure windows open, MATLAB targets the one that is
designated the "current Iigure" (the last Iigure used or clicked in). To make an existing Iigure
window the current Iigure, you can click the mouse while the pointer is in that window or you
can type
figure(n)
where n is the number in the Iigure title bar. The results oI subsequent graphics commands are
displayed in this window. To open a new Iigure window and make it the current Iigure, type
figure
Clearing the Figure for a New Plot
When a Iigure already exists, most plotting commands clear the axes and use this Iigure to create
the new plot. However, these commands do not reset Iigure properties, such as the background
color or the colormap. II you have set any Iigure properties in the previous plot, you might want
to use the clf` command with the reset option,
clf
reset
beIore creating your new plot to restore the Iigure's properties to their deIaults.
Miscellaneous Commands
Command What does it do?
clear Removes items Irom workspace, Ireeing up system memory
close all Deletes all Iigures (whose handles are not hidden)
cla Clears current axes
grid on ads major grid lines to the current axes.
clI Clears current Iigure window
Important points to remember:
plot3(1,2,3) plots the point (x1,y2,z3) in space while plot3([ 1j,[ 2j,[ 3j) plots the
position vector oI such point in space.
EXERCISES:
1. Consider a time varying scalar Iunction given by
S
(t)
10cos(at )
Take a suitable range Ior t and generate a movie diIIerent plots oI S
(t)
. Hint: Take number oI
Iramesk24 and tk/10)
uutput and Comments:
EXAMPLE OUTPUT
2. Consider a vector Iunction VV
x
+V
y
+V
z
have Iollowing components in
Cartesian Co-ordinate system
V
x
10cos(at)
V
y
20cos(at )
V
z
30cos(at- )
Simulate variations in vector V using movie and getIrame Iunction. In the same Iigure,
simulate this vector at point(1,2,3) at diIIerent instants oI time t` .
uutput and Comments:
3--Consider a time varying vector VV
x
+V
y
+V
z
given by Iollowing components
V
x
10cos(O)
V
y
20cos(Oa/3)
V
z
30cos(O- a/3)
Where angle O varies Irom 0 to 1.9 a
(a). Use subplot and Iigure commands to develop two simulation Iigures. One showing
variations oI all three components with time (similar to problem 1) and the other Iigure
showing variations oI vector V in space. Use * as graph marker.
(b) .What type oI vector is V?
uutput and Comments
4-A time varying vector VV
x
+V
y
+V
z
given by speciIic component Iunctions is called
general time varying vector Iunction. It may or may not be a harmonic Iunction. Consider one oI
such vector Iunctions given by its components
V
x
10t
V
y
2t
2
V
z
3(t
3.5
)
Let t such that -10_ t _10, Use subplot and Iigure commands to develop two simulation Iigures.
One showing variations oI all three components with time and the other Iigure showing
variations oI vector V in space. Use * as graph marker.
uutput and Comments:
Simulation of space varying and time varying scalar
and vector fields using MATLAB
Theory:
A Iield ( scalar or vector) may be deIined mathematically as some Iunction oI that vector which
connects an arbitrary origin to a general point in space.
Scalar and Vector fields.
A Iield corresponds to a general Iunction which have set oI all possible position vectors as it`s
domain. II E(r) (Iunction E oI position vector r) is always a scalar quantity Ior all r then E(r)
is a scalar Iield e.g. temperature throughout a bowl, density oI Earth at a point. II however,
E(r) is always a vector quantity Ior all possible r values then E(r) is a vector Iield. II we
consider Earth`s magnetic Iield as E(r), then we need to express both magnitude and direction
oI magnetic Iield at point deIined by the position vector r (i.e. E(r) is a vector). Similarly,
gravitational Iield oI Earth, gradient oI temperature and gradient oI voltage are examples oI
vector Iields.
Both scalar and vector Iield in turn can be time-constant or time-varying in nature depending
on whether these remain constant or vary with time respectively.
The 'shading ' function :
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:07
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
CuMMENTS:
The 'pause ' function:
The 'rotate3d' function :
Example:
Exercise:
Q1 : Consider a Iunction S (-2x2;-1y1) .
(a) Generate a scalar plot oI Iunction S using meshgrid on XY plane and magnitude oI
solution oI Iunction S on z axis (use surI and shading commands Ior surIace ). What
does this Iigure depicts about Iunction S ?
(b) Use pause command and generate a second Iigure showing a vector Iield oI gradient
vectors oI above Iunction.(use gradient along with quiver command)
Don`t Iorget to allow 3D rotations Ior the Iirst case!
uutput and Comments:
Q2 : Consider a Iunction S` (-2x2;-1y1) take t 0.1(nIrames)
(a) Generate a movie that animate a surIace oI above Iunction |surIace similar to that in
Q1 (a)
(b) How would you diIIerentiate between the two scalars Iields S and S`?
uutput and Comments:
Demonstrating the Dot and Cross product of Vectors
using Matlab.
Theory:
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:08
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
The 'zeros' function:
The 'ones' function:
Exercise:
The Iollowing code plots two 2D vector Iields A and B. The Iields are plotted using rectangular
components ( Ax, Ay, Bx, By ). Add a code to
(a) Generate a surIace plot representing A.B (Hint: A.BAx.*Bx Ay.*By)
(b) Generate another plot showing AB
uUTPUT AND CuMMENTS:
Simulating gradient of a scalar field using MATLAB.
Theory:
Cradient of scalar field:
Cradlent ol scalar ls a vector whlch shows maxlmum space rate ol change ol such quantlty and the
dlrectlon ln whlch thls maxlmum occurs.
The 'gradient' function :
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:09
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
returns output.
Fig: Gradient vectors shown as arrows at various points for a scalar field
Exercise:
The Iollowing code plots a 2-Dimensional Iunction sx. in 3D such that z-axis is the
value oI Iunction s
(x , y)
Ior x, y domain ( meshgrid oI x and y). Write a code to obtain gradient
plot Ior such surIace.
uUTPUT AND CuMMENTS:
Simulating divergence of a vector field
Theory:
The 'divergence' function:
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:10
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
Note: wind` is a library workspace Iile (.mat Iile) that deIines variables ( x, y, z, u, v and w) such
that u, v and w are rectangular-wind-velocity-components at lattice points (x y z).ReIer to MATLAB
help Ior details (search Ior Overview oI Volume Visualization`)
uutput figure:
Exercise:
Use resultant vector Iield oI experiment#9 to get a divergence plot.
Simulating Curl of vector field
Theory:
The "Curl" Function:
Computes the Curl and angular velocity oI a vector Iield.
Syntax:
|curlx,curly,curlz,cav| curl(X,Y,Z,U,V,W)
|curlx,curly,curlz,cav| curl(U,V,W)
|curlz,cav| curl(X,Y,U,V)
|curlz,cav| curl(U,V)
|curlx,curly,curlz| curl(...)
|curlx,curly| curl(...)
cav curl(...)
Description:
|curlx,curly,curlz,cav| curl(X,Y,Z,U,V,W) computes the curl and angular velocity
perpendicular to the Ilow (in radians per time unit) oI a 3-D vector Iield U, V, W. The arrays X,
Y, Z deIine the coordinates Ior U, V, W and must be monotonic and 3-D plaid (as iI produced by
meshgrid).
|curlx,curly,curlz,cav| curl(U,V,W) assumes X, Y, and Z are determined by the expression |X
Y Z| meshgrid(1:n,1:m,1:p)
where |m,n,p| size(U).
|curlz,cav| curl(X,Y,U,V) computes the curl z-component and the angular velocity
perpendicular to z (in radians per time unit) oI a 2-D vector Iield U, V. The arrays X, Y deIine
the coordinates Ior U, V and must be monotonic and 2-D plaid (as iI produced by meshgrid).
|curlz,cav| curl(U,V) assumes X and Y are determined by the expression
|X Y| meshgrid(1:n,1:m)
where |m,n| size(U).
|curlx,curly,curlz| curl(...),
curlx,curly| curl(...) returns only the curl.
cav curl(...) returns only the curl angular velocity.
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:11
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
Example:
This example uses colored slice planes to display the curl angular velocity at
specified locations in the vector field.
load wind
cav curl(x,y,z,u,v,w);
slice(x,y,z,cav,|90
134|,|59|,|0|); shading interp
daspect(|1 1 1|); axis
tight camlight
uutput Figure:
The "Size" Function:
Array dimensions
Syntax
d size(X)
|m,n|
size(X) m
size(X,dim)
|d1,d2,d3,...,dn| size(X)
Description
d size(X) returns the sizes oI each dimension oI array X in a vector d with ndims(X)
elements. |m,n| size(X) returns the size oI matrix X in separate variables m and n.
m size(X,dim) returns the size oI the dimension oI X speciIied by scalar
dim. |d1,d2,d3,...,dn| size(X) returns the sizes oI the Iirst n dimensions oI array X in
separate variables. II the number oI output arguments n does not equal ndims(X), then Ior:
n ~ ndims(X)size returns ones in the "extra" variables, i.e., outputs ndims(X)1 through n.
n ndims(X)dn contains the product oI the sizes oI the remaining dimensions oI X, i.e.,
dimensions n1 through ndims(X).
Example:
The size oI the second dimension oI rand(2,3,4) is 3. m size(rand(2,3,4),2)
m
3
Here the size is output as a single vector. d size(rand(2,3,4))
d
2 3 4
Here the size oI each dimension is assigned to a separate variable
|m,n,p| size(rand(2,3,4))
m
2
n
3
p
4
The "Hold" Function:
Hold current graph in the Iigure
Syntax:
hold on
hold oII
hold all
hold(axeshandle,...)
Description:
The hold Iunction determines whether new graphics objects are added to the graph or replace
objects in the graph. hold on retains the current plot and certain axes properties so that
subsequent graphing commands add to the existing graph. hold oII resets axes properties to
their deIaults beIore drawing new plots. hold oII is the deIault. hold all holds the plot and the
current line color and line style so that subsequent plotting commands do not reset the
ColorOrder and LineStyleOrder property values to the beginning oI the list. Plotting
commands continue cyclicing through the predeIined colors and linestyles Irom where the last
plot stopped in the list. hold toggles the hold state between adding to the graph and replacing
the graph. hold(axeshandle,...) applies the hold to the axes identiIied by the handle
axeshandle.
Exercise:
The following code plots a two dimensional vector field P x + y in 3D. Write the code
to obtain curl and magnitude of curl plot of this vector field.
Curl oI a vector Iield
close all; clear;
x -1:0.1:1; y -1:0.1:1;
|xx,yy| meshgrid(x,y);
px exp(-(xx.`2yy.`2));
py sin(xx.*yy);
Iigure;quiver(x,y,px,py,2);
xlabel('x');ylabel('y');
title('2-D vector Iield: \bI P} e`-(x`2y`2)}\bI x} sin(xy) \bI y} ');
pause;
OUTPUT AND COMMENTS:
Sketching Fields due to discrete and line charge
distributions in Matlab
Theory:
Electric Iield is deIined as the electric Iorce per unit charge. The direction oI the Iield is taken to
be the direction oI the Iorce it would exert on a positive test charge. The electric Iield is radially
outward Irom a positive charge and radially in toward a negative point charge.
Electric Field due to discrete charge:
The electric Iield oI a point charge can be obtained Irom Coulomb's law:
The electric Iield is radially outward Irom the point charge in all directions. The circles represent
spherical equipotential surIaces.
The electric Iield Irom any number oI point charges can be obtained Irom a vector sum oI the
individual Iields. A positive number is taken to be an outward Iield; the Iield oI a negative charge
is toward it.
This electric Iield expression can also be obtained by applying Gauss' law
Eig.1 Electric Iield oI a discrete positive charge and negative charge.
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:12
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
Electric Field of a line charge distribution:
Electric Iield oI a line charge distribution is obtained by superposing the point charge Iields oI
inIinitesimal charge elements. Eield due to a uniIorm positive line charge distribution is directed
outwards while oI negative charge distribution is directed inwards. The radial part oI the Iield
Irom a charge element is given by
The integral required to obtain the Iield expression is
The "slice" Function:
The 'colorbar' function:
Example:
The following example illustrates the plotting of field of a point charge in log
magnitude located at the origin.
uutput Figure:
Simulation of Vector fields with and without
sourcesJsinks using MATLAB
Theory:
The Divergence :
In vector calculus, the divergence is an operator that measures the magnitude oI a vector Iield's
source or sink at a given point; the divergence oI a vector Iield is a (signed) scalar. Eor a vector
Iield that denotes the velocity oI air expanding as it is heated, the divergence oI the velocity Iield
would have a positive value because the air expands. II the air cools and contracts, the
divergence is negative. The divergence could be thought oI as a measure oI the change in
density.
Physical Significance uf Divergence:
In physical terms, the divergence oI a three dimensional vector Iield is the extent to which the
vector Iield Ilow behaves like a source or a sink at a given point. It is a local measure oI its
"outgoingness"the extent to which there is more exiting an inIinitesimal region oI space than
entering it. II the divergence is nonzero at some point then there must be a source or sink at that
position
The SourcesJSinks uf A Vector Field And The Divergence :
Consider water -Ilux analogy. Regions oI positive divergence are "taps" (sources), regions oI
negative divergence are sinks, water represents Ilux
At any point where the divergence is zero (no sources or sinks), the water Ilowing in must equal
the water Ilowing out. Hence iI the divergence is zero, we can conclude that there is no net Ilux
and thus there are no sources or sinks present at that point. Conversely, iI the net Ilux is non-
zero, that indicates that water is being added by a source (positive divergence) at that point, or
being taken away (negative divergence) by a sink.
Exercise:
Consider two vector Iields given by:
and
(a) Generate quiver plots oI both Iunctions
(b) Also generate divergence plots (using surI command)
(c) Observe careIully the divergence plots and identiIy the vector Iield with sinks or sources
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:13
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
uUTPUT AND CuMMENTS:
Simulation of motion of an electron in an electrostatic
field using MATLAB
Theory:
Eollowing method is one oI several to simulate a moving electron in a uniIorm
electrostatic Iield using MATLAB:
The electrostatic Iorce on a charge q moving with a velocity (V) in a uniIorm electric
Iield (E) is given by:
F qE eE (a)
Where F and E are vector quantities.
In Cartesian co-ordinate system, the rectangular components oI E and E are given by
FE
x
a
x
+E
y
a
y
+E
z
a
z
(b)
EE
x
a
x
+E
y
a
y
+E
z
a
z
(c)
Now consider an electron (massm
e
-1.6e-19Kg; chargee-9.31e-31C) being projected to a
uniIorm electric Iield E with initial velocity v
0
. The acceleration produced in the electron as a
result oI application oI electrostatic Iorce is given by Newton`s second law:
aF/m
e
Using equations (a) and (b), above equation becomes:
a ( E
x
a
x
+E
y
a
y
+E
z
a
z
) (d)
The initial-velocity Vo have Iollowing rectangular components :
V
0
v
x
a
x
v
y
a
y
v
z
a
z
The position vector r
0
gives initial position oI electron and can also be resolved into rectangular
components.
We are interested in Iinding the position vector r oI electron aIter time t`. Eor this, we
consider only xcomponents oI all above vector quantities Ior the sake oI simplicity. Now we use
second equation oI motion to Iind x-component oI position vector. The general equation Ior body
moving in a straight line is given as:
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:14
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
Where s distance aIter time t
s
o
initial position
v
o
initial velocity
u acceleration in body
t time interval oI initial and Iinal instances oI time.
I|gure 1 Mot|on of e|ectron through un|form e|ectrostat|c f|e|d
We can now happlly apply thls relatlon to llnd r
x
. uslng eq. (d) and above equatlon we llnally
have
r
x
= r
ox
+ v
ox
t + (1)
1he y and z components are obtalned on slmllar grounds
r
y
=r
oy
+ v
oy
t + (2)
r
z
=r
oz
+ v
oz
t + (3)
Above relatlons are used to obtaln the x, y and z-components ol posltlon vector ol movlng
electron alter tlme lnterval 't'. 1hese components are plotted to obtaln tra[ectory ol electron ln
3u.
EXERCISE:
(a) An electron ls pro[ected to a reglon contalnlng an Llectrlc lleld lntenslty [Lx Ly Lz]=[0
100 0] vm
-1
. ll the lnltlal veloclty ls [vx vy vz]=[ 200 0 0 ] ms
-1
at orlgln, generate a
code to obtaln a 3u plot showlng path ol motlon ol electron lor the tlme lnterval
t=0:10e-9:100e-9 sec.
(b) Cenerate at least two dlllerent paths by uslng arbltrary L,v and t values .
uUTPUT AND CuMMENTS:
Example Output
Cradient of Functions:
uB)ECTIVE:
The objectives oI this lab session are to:
(i) How to determine the gradient oI any Iunction
(ii) Be Iamiliar with built in Iunction oI gradient
Examples:
Example1:
|x,y|meshgrid(-
2:0.2:2); zx.*exp(-
x.`2-y.`2);
|dx,dy|gradient(z,0.2,0
.2); contour(x,y,z);
hold on
quiver(x,y,dx,
dy); colormap
hsv; hold oII;
uUTPUT & CuMMENTS:
RESULT:
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:15
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
Example.2:
|X,Z|meshgrid(-2:0.1:2);
Ylog(X.`2).*exp(Z);
|DX,DZ|gradient(Y,0.1,0.1);
contour(X,Y,Z);
hold on
quiver(X,Y,DX,DZ);
colormap hot;
hold oII;
uUTPUT & CuMMENTS:
RESULT:
Example.3:
|X,Y|meshgrid(-2:0.1:2);
ZX.*exp(log(Y));
|DX,DY|gradient(Z,0.1,0.1);
contour(X,Y,Z);
hold on
quiver(X,Y,DX,DY);
colormap hot;
hold oII;
RESULT:
Home work:
Eind the gradient oI Iollowing Iunctions:
(i)
(ii)
Convert a point fromrectangular coordinate system
into the spherical coordinate system.
uB)ECTIVE:
Using the MATLAB program, convert a point Irom rectangular coordinate system into the
spherical coordinate system.
THEuRY:
In this practical MATLAB programming is used to convert a point Irom one coordinate System
to another coordinate system. Let us suppose it is required to Iind the Cylindrical point (p , )
Irom the rectangular coordinates (x,y).
Eollowing steps are used to implement the program
Thr 3s|ania Oniurrsitv e| Tahaa|nr
Un|vers|ty Co||ege of Lng|neer|ng & 1echno|ogy
Electromagnetic Field Theory EE-224
Electrical Engineering {4
th
Semester]
LAB EXPERIMENT:16
:NO:01
Name: Roll No:
Lab Instructor Signature: Date:
MATLAB CuDINC:
Type the above MATLAB coding in the MATLAB programming editor and save the Iile. Now
run the program and get the output on the command window.