EEM 201-CIRCUIT THEORY

LAB 01: Introduction to MATLAB

Pre-Lab and Warm-Up: You should read at least the Pre-Lab and Warm-Up sections of this lab assignment and go over all exercises in Pre-Lab section before going to your assigned lab session.

Lab Report: It is necessary to turn in a report on Section 3 with graphs and explanations. In order to keep track of plots, include your plots within your report. If you are unsure about what is expected, ask the TA who will grade your report.

1 Pre-Lab

Make sure that you read through the information below prior to coming to lab. We will be going over the commands in this section during the lab. session.

1.1 Overview

MATLAB will be used extensively in all the labs. Primary goal of this lab is to familiarize you with using MATLAB. Here are three specific goals for this lab:

1. Learn basic MATLAB commands and syntax, including the help system.

2. Learn to write and edit your own script files in MATLAB, and run them as commands.

3. Learn a little about advanced programming techniques for MATLAB, i.e., vectorization.

1.2 What is MATLAB?

MATLAB is a product of MathWorks, Inc. and is an advance interactive software package specially designed for scientific and engineering numerical computation. The MATLAB (Matrix Laboratory) environment integrates graphics illustrations with precise numerical calculations and is a powerful, easy-to-use and comprehensive tool for performing all kinds of computations and scientific data visualizations. MATLAB has proven to be a very flexible and usable tool for solving problems in applied mathematics, physics, chemistry, engineering, medicine, finance and other application areas which deal with complicated numerical calculations. MATLAB is also and excellent pedagogical tool when teaching mathematics, numerical analysis and engineering. The program is widely used at universities all around the world and its popularity for industrial use is rapidly increasing. MATLAB is available on machines ranging from personal computers to super computers.

1.3 Getting Started

After logging in, you can start MATLAB by double-clicking on the MATLAB icon, typing matlab in a terminal window, or by selecting MATLAB from a menu such as the START menu under Windows-95/98/NT/XP.

The following steps will introduce you to MATLAB.

a. View the MATLAB introduction by typing intro at the MATLAB prompt. This short introduction will demonstrate some of the basics of using MATLAB.

b. Run the MATLAB help desk by typing helpdesk. The help desk provides a hypertext interface to the MATLAB documentation. The MATLAB preferences can be set to use Netscape or Internet Explorer as the browser for help. Two links of interest are Getting Help (at the bottom of the right-hand frame), and Getting Started, which is under MATLAB in the left-hand frame.

c. Explore the MATLAB help capability available at the command line. Try the following:

help

help plot

help colon %<--a VERY IMPORTANT notation

help ops

help zeros

help ones

lookfor filter %<--keyword search

NOTE: It is possible to force MATLAB to display only one screen-full of information at once by issuing the command more on).

d. Run the MATLAB demos: type demo and explore a variety of basic MATLAB commands and plots.

1.4 Basic Commands, Syntax, and Information

1.4.1 Number and Data Representation

The approximate range of numbers that can be represented in MATLAB is from 10-308 to 10308. Very large or very small numbers can be represented using exponents. Typical examples of valid number representations are as follows:

123456789 123456789e3 1234.56789

123456.789E-2 1.23456789e3 -1234.56789

There should be no blank space before the exponent.

The data in MATLAB are represented in the form of a rectangular matrix that does not require dimensioning. Its elements can be either real or complex numbers.

Ex 1: x=[3.5+4*j -2.1-7.4*j 3.5 2 9.2*j];

The imaginary part of a complex number is represented using the operator * and the letters j or i.

The clear variable command is used for clearing a specific variable (e.g. clear x). The clear command is used for clearing all the variables, arrays, and matrices stored.

The elements in the row of a matrix can also be separated by commas as indicated below:

x=[3.5+4*j, -2.1-7.4*j, 3.5, 2, 9.2*j];

The semicolon (;) at the end of the square brackets ensures that the data are not printed in the command window after they have been entered.

Observe what will happen if you do not use semicolon(;)in Ex 1.

Alternately, if needed, the actual value of x can be printed by typing x in the Command Window.

The elements of a matrix can be entered in two different ways. The rows can be typed on a single line separated with semicolon or on different lines. For example, the 3x4 matrix A can be entered either as

A=[1 3 5 7; 2 4 6 8; 9 11 13 15];

or as

A=[1 3 5 7

2 4 6 8

9 11 13 15];

!!! The indexing of vectors and matrices in MATLAB begins with 1. The index cannot be less than 1 or greater than the dimension of the vector or matrix under consideration.

For example the first element in the first row of a matrix A is given by A(1,1).

The size of an array in the workspace of MATLAB can be determined by using the function size. For example, by typing size(x) we obtain the result

ans =

1 5

The length of a vector can also be found by using the function length. For example, typing length(x) yields the result

ans =

5

The array transpose operation is implemented using the operator (.’). Thus the transpose of x is given by the expression (x.’).

!!! MATLAB differentiates between lowercase and uppercase letters. This means you can use a and A as variable names to indicate two different variables.

Ex 2: Let X denote the 3x4 real-valued matrix entered by typing

X=[1 2 3 4; 5 6 7 8; 9 10 11 12]

Observe the difference between X and X’ in Ex 2 by typing X’ in the command window.

1.4.2 Arithmetic Operations

We use + and – operators to add or subtract scalars and matrices. In order to perform these operations on matrices, the dimensions of the matrices must be same.

In MATLAB to perform dot product, the function .* and to perform cross product, the function * are used.

Matrix right division X/Y is equivalent to X*inv(Y) where inv(Y) denotes the inverse of Y. If X and Y are of the same dimension, the array right division is implemented using the expression X./Y, resulting in a matrix whose (r,s)-th element is given by X(r,s)/Y(r,s).

!!! If multiple operations are employed in a statement, the usual precedence rules are followed in evaluating the expression. However, parentheses can be used to change the precedence of operations.

Ex 3: Let X=[1 2 3; 4 5 6] and Y=[12 11 10; 9 8 7]

Observe the results of the operations: X+Y, X-Y, X+3, X*3, X.*Y, X*Y’, X’*Y .

Ex 4: Let X=[1 2 3; 4 5 6; 7 8 9] and Y=[1 1 2; 2 2 3; 1 3 4]

Observe the results of the operations: X/Y, X/2 .

1.4.3 Relational and Logical Operations

Element-by-element comparisons between two matrices of the same size are carried out using these operators with the result appearing as a matrix of the same size whose elements are set to1 when the relation is TRUE and set to 0 when the relation is FALSE.

Ex 5: Let C=[1 2 3; 4 5 6] and D=[1 7 2; 6 5 1]

Observe the results of the operations: C<D, C>D, C<=D, C>=D, C==D, C~=D .

Same way with the relational operators are used, logical operators &, |, ~ can be used to perform AND, OR, NOT operations.

Ex 6: Let A=[1 1 0 1] and B=[0 1 0 0]

Observe the results of the operations: A&B, A|B, ~A.

1.4.4 M-Files

An M-file is a sequence of MATLAB statements developed using a word processor or a text editor and save with a name that must be in the form filename.m. Certain characters, such as hyphen (–) and decimal point (.), are not allowed in the names.

!!! Do not use the names of existing M-files.

2 Exercises

a) Use MATLAB as a calculator. Try the following:

pi*pi-10

sin(pi/4)

ans^2 %<---“ans” holds the last result

b) Do variable name assignment in MATLAB. Try the following:

x=sin(pi/5)

cos(pi/5) %<---assigned to what??

y=sqrt(1-x*x)

ans

c) Complex numbers are natural in MATLAB. The basic operations are supported. Try the following:

z=3+4i,w=-3+4j

real (z), imag (z)

abs ([z,w]) %<--- Vector constructor

conj(z+w)

angle(z)

exp(j*pi)

exp(j*[pi/4, 0, -pi/4])

d) Make sure that you understand the colon notation. In particular, explain in words what following MATLAB code will produce.

Jkl=0:6

Jkl=2:4:17

Jkl=99:-1:88

ttt=2:(1/9):4

tpi=pi*[0:0.1:2];

e) Extracting and/or inserting numbers into a vector is very easy to do. Consider the following definition of xx:

xx=[zeros(1,3), (0:0.25:1), ones(1,4)]

xx(4:6)

size(xx)

length(xx)

xx(2:2:length(xx))

Explain the results echoed from the last four lines of the above code.

f) Observe the result of the following assignments:

yy=xx; yy(4:6)=pi*(1:3)

Now write a statement that will take the vector xx defined in part (e) and replace the even indexed elements (i.e., xx(2), xx(4), etc.) with a constant. Use a vector replacement, not a loop.

g) Experiment with vectors in MATLAB. Think of the vector as a set of numbers. Try the following:

xk=cos(pi*(0:11)/4) %<---comment: compute cosines

What is xk(1)? Is xk(0) defined?

!!! The text following the % is a comment, it may be omitted.

h) (A taste of vectorization) Loops can be written in MATLAB, but they are NOT the most efficient way to get things done. It’s better always avoid loops and use the colon notation instead. The following code has a loop that computes values of the cosine function (The index of yy() must start at 1). Rewrite this computation without using the loop (follow the style in the previous part).

yy=[]; %<---initialize the yy vector to be empty

for kk=-5:5

yy(k+6)=cos(k*pi/3)

end

yy

Why it is necessary to write yy(k+6). What happens if you use yy(k) instead?

i) Plotting is easy in MATLAB for both real and complex numbers. The basic plot command will plot a vector y versus a vector x connecting successive points by straight lines. Try the following:

x= [-3 –1 0 1 3];

y=x.*x-3*x;

plot(x,y)

z=x+y*sqrt(-1)

plot (z) %<---complex values: plot imag vs. real

Use help arith to learn how the operation xx.*xx works when xx is a vector; compare to matrix multiplication.

When unsure about a command, use help.

j) Use the built-in MATLAB editor (on Windows 95/98/NT/XP), or an external one such as EMACS on UNIX/LINUX, to create a script file called mylab1.m containing the following lines:

tt=0:0.01:1;

xx=cos (5*pi*tt);

zz=1.4*exp(j*pi/2)*exp(j*5*pi*tt);

plot(tt, xx, ’b-‘, tt, real(zz), ’r—‘), grid on

%<--- plot a sinusoid

title (‘TEST PLOT of a SINUSOID’)

xlabel (‘TIME (sec)’)

k) Run your script from MATLAB. To run the file mylab1 that you created previously: mylab1 %<--- will run the commands in the file

type mylab1 %<--- will type out the contents of

% mylab1.m to the screen

l) Generate a time vector (t) to cover a range of t that will exhibit two cycles (from –T to T) of a sinusoid defined below with f=4000 Hz. We will use T to denote the period (cycle) of the sinusoids and define the starting time of the vector t to be equal to –T, and the ending time as +T. You should be using a definition for t similar to tt in part (2.j). Make sure that you have at least 25 samples per period of the sinusoidal wave. Make a plot of this signal.

x(t)=Acos(2pft)

3 Lab Homework: Manipulating Sinusoids with MATLAB

Now you’re on your own. Create new m-files for the following exercises and include your m-files of this Section with plots in your Homework Report.

(a) Generate two sinusoids with a frequency of 4000 Hz and with amplitudes and time-shifts as indicated below.

x1(t)=A1cos(2p(4000)(t-tm1))

x2(t)=A2cos(2p(4000)(t-tm2))

A1=your age (e.g.19)

A2=1.2A1

tm1=(37.2/M)T

tm2=-(41.3/D)T

D and M are the day and month of your birthday, and T is the period of a cosine function.

Make a plot of both signals over the range of –T_t_T:

-use subplot(2,1,1) and subplot(2,1,2) to make a two-panel figure that puts both of the plots in the same figure window. See help subplot.

-use hold to make a single-panel figure that will hold both signals in one window. See help hold.

(b) Create a third sinusoid as the sum: x3(t)=x1(t)+x2(t). In MATLAB this amounts to summing the vectors that hold the values of each sinusoid:

-Make a plot of x3(t) over the same range of time as used in the plots of part (a). Include this as the third panel in the plot by using subplot(3,1,3). Hint: You will need to change the subplot settings in the previous example.

-Now make a new plot including x1, x2, and x3 by using hold command.

(c) Before printing these four plots, put a title on each subplot, and include your name in one of the titles. With your plots, also include labels by using xlabel(‘text’) and ylabel(‘text’) commands (use time(sec) for x-axis, amplitude(V) for y-axis). See help title, help xlabel, help ylabel, help print and help orient, especially orient tall.