Professional Documents
Culture Documents
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).
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
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 ]
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
>>doc plot
>>doc for
>>doc subplot
>>doc roots
What is the difference between help and dot? What do you learn about these
commands? Record your observation:
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.
y = x5 – 3x3 + 7
y = 745x9 – 384x4 + 7
OUTPUT & COMMENTS:
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:
>>for m= 1 : 3
>> for n= 1 : 3
>> x(m,n) = m+n*i;
>>end
>>end
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
>>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?
% This is a comment
While doing your homework assignments make sure that you include essential
comments to elaborate your program.
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.
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.
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.
>>A = 5;
>>B = MY_FUNCTION (A)
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
value. Test your program.
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
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.
>>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.
>>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?
OUTPUT & COMMENTS:
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.
You will have encountered INF and NAN in the output of above commands. Explain
them:
OUTPUT & COMMENTS:
>> u.^2
>> u.^4
>> u.*w.^(-2)
OUTPUT & COMMENTS:
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)
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'
z2 + r2 = ρ2 x2 + y2 = r2 x2 + y2 + z2 = ρ2
tanΦ = r/z tanθ = y/x tanθ = y/x
>>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)