PC-MATLAB Primer

R. A. Kolk

Adjunct Prof. of Electrical Engineering

University of Hartford

This primer to PC-MATLAB is intended for use by University of Hartford students enrolled in various engineering courses including; EE341, ES440, and EE442. Complete PC-MATLAB manuals can be purchased by contacting; The Mathworks, Inc., 158 Woodland St., Sherborn, Mass.,01770, (617) 653-1415.

PC-MATLAB is an interactive matrix manipulation program available in the University of Hartford's microcomputer lab located in the basement of the United Technologies Building. As a user of PC-MATLAB you will need two (MS-DOS) formatted 5.25 inch floppy disks. These disks can be formatted in the lab, just ask the student in charge for assistance. You will also need to familiarize yourself with the file editor available on the microcomputer network as you will be creating and editing files.

1. INVOCATION and EXIT:

The following procedure is used to invoke PC-MATLAB on the University of Hartford system:

1) Turn on or boot up the terminal

2) Set the keyboard to lower case, PC-MATLAB is case sensitive it will operate "only" in lower case

3) Enter appropriate responses for login information prompted

(note: the user number is the number on your terminal)

4) Select PC-MATLAB on the program menu

5) Make sure you insert your floppy disk into drive a when you are prompted

6) The following message will appear when you have successfully entered PC-MATLAB

< P C - M A T L A B >

(c) Copyright The MathWorks, Inc. 1984, 1985, 1986

All Rights Reserved

Version 2.02 22-Jan-86

HELP and DEMO are available

>>

The >> is the PC-MATLAB prompt and means that PC-MATLAB s ready to accept information

A PC-MATLAB session may be terminated in two ways;

1) Entering "quit" at the PC-MATLAB prompt will exit you from PC-MATLAB but will not save any of your PC-MATLAB results.

2) Entering "save" followed by "quit" at the PC-MATLAB prompt will save all of your PC-MATLAB results in a file named matlab.mat on your floppy disk and then exit you from PC-MATLAB. In a subsequent session, these saved results may be loaded back into your PC-MATLAB workspace by entering "load" at the PC-MATLAB prompt.

2. DATA REPRESENTATION AND METHODS OF INPUT:

PC-MATLAB works with one kind of object, a rectangular numerical matrix with possibly complex elements. In some situations, special meaning is attached to 1-by-1 matrices, which are scalars, and to matrices with only one row or column, which are vectors. There are no dimension statements or type declarations in the PC-MATLAB language. Storage is allocated automatically, up to the amount available on any particular computer.

Matrix data is introduced into PC-MATLAB in two basic ways:

1) Interactively, elements are either typed in or generated using various built in functions. The explicit list of matrix elements is separated by blanks or commas, is surrounded by brackets, [ and ], and uses the semicolon ; to indicate the ends of the rows. For example, entering the statement

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

results in the output

a =

1 2 3

4 5 6

7 8 9

Large matrices can be spread across several input lines, with carriage returns replacing the semicolons. The above matrix could also have been produced by three lines of input,

a = [ 1 2 3

4 5 6

7 8 9 ]

Big matrices can be constructed using little matrices as elements. For example, another row could be attached to the matrix a with the command

a = [a; [ 10 11 12] ]

which produces

a = [ 1 2 3

4 5 6

7 8 9

10 11 12 ]

2) Off Line, elements are created by a user written function program (referred to as a .m file in PC-MATLAB). These files are created using the editor program and will reside on your floppy disk. As an example, suppose you were shopping for a loan or mortgage and wanted to evaluate the monthly payment (mp, in dollars) for various principal amounts (p, in dollars), interest rates (i, yearly rate in percent), and loan durations (n, in months). The formula to be evaluated is:

-n

mp = (p*i/(100*12)) / 1 - (1 + i/(100*12))

A .m function file named "broke.m" is created using the editor. Its contents are listed below;

function mp=broke(p,i,n)

%

% function mp=broke(p,i,n)

% inputs: p = principal amount, dollars

% i = yearly interest rate, percent

% n = duration of loan, months

% outputs: mp = monthly payment, dollars

%

ii=i/(100*12);

tmp=(1 + ii)^-n ;

mp=p*ii/(1-tmp);

Remarks:

1) All lines begin in column 1.

2) The percent symbol (%) signifies a comment line in PC-MATLAB. A good practice is to duplicate the function call line as a comment line as the second line in any function you create, then typing "help broke" while in PC-MATLAB will list the comment line which is the functional form of the broke.m function in case you forget how to invoke the function while in PC-MATLAB.

3) In addition to duplicating the function call it is a good idea to define the inputs, outputs, and their units is subsequent comment lines. This provides you with concise documentation.

4) The semicolon (;) at the end of a line is used to suppress the echo of the calculation. It is a good idea to suppress all echo's in a function. If you desire an echo, simply remove the semicolon.

3. MATRIX OPERATIONS:

Matrix operations are fundamental to PC-MATLAB, a list of the most common operations is presented below:

' transpose

* multiply

.* element by element multiply

/ right division

./ element by element right division

+ add

- subtract

inv inverse (for square matrices)

pinv pseudo-inverse (for non square matrices)

Example:

Solve the set of linear equations for [x y z] given

x + 2y + z = 4

y - 2z = 8

x - 5y + 3z = 0

Formulate as a matrix problem, where v = a*p, with

v = [4 8 0]'

a = [1 2 1; 0 1 -2; 1 -5 3]

p = [x y z]'

Then, p = inv(a)*v

4 RELATIONAL AND LOGIC OPERATORS:

There are six relational operators which can be used to compare two matrices of equal dimension.

< less than

<= less than or equal

> greater than

>= greater than or equal

== equal

~= not equal

There are three logical operators which work element-wise and are usually used on 0-1 matrices.

& and

| or

~ not

5 COLON NOTATION:

The usual way of referencing submatrices is using colons. The colon notation allows access to submatrices and other chunks of arrays. suppose that a is an n-by-n matrix. Then

a(1:5,3)

specifies the 5-by-1 submatrix, or column vector, consisting of the first five elements in the third column of a. Similarly,

a(1:5,n-3:n)

is the 5-by-4 submatrix of elements from the first five rows and the last four columns. Using the colon by itself in place of a subscript denotes all of the corresponding row or column. For example,

a(:,3)

is the third column and

a(1:5,:)

is the first five rows. Fairly sophisticated effects are obtained using submatrix referencing on both sides of an assignment statement. For example,

a(:,[3 5 10]) = b(:,1:3)

replaces the third, fifth, and tenth columns of a with the first three columns of b.

6 CONTROL FLOW:

PC-MATLAB has control flow statements, like those found in most computer languages. The control flow statements carry PC-MATLAB beyond the level of a simple desk calculator, to become a complete high level matrix language.

FOR loops:

PC-MATLAB has its own version of the "do" or "for" loop found in computer languages. It allows a statement, or group of statements, to be repeated a fixed, predetermined number of times. For example

for i=1:n, x(i)=0, end

will assign 0 to the first n elements of x. If n is less than 1, the construction is still legal, but the inner statement will not be executed. If x does not yet exist, or has fewer than n elements, then additional space will be allocated automatically. The loops can be nested, and are usually indented for readability.

for i=1:m

for j=1:n

a(i,j)=1/(i+j-1);

end

end

a

The semicolon terminating the inner statement suppresses repeated printing and the a after the loops displays the final result. An important point: each for MUST be matched with an end.

WHILE loops:

PC-MATLAB also has its version of the "while" loop, which allows a statement, or group of statements, to be repeated an indefinite number of times, under control of a logical condition. Here is a simple problem to illustrate w while loop. What is the first integer n for which n! is a 100 digit number? The following while loop will find it. If you don't already know the answer, you can run this yourself.

n=1;

while prod(1:n)<1.e100, n=n+1; end

n

7 GRAPHICS:

Scientific and engineering data are examined graphically in PC-MATLAB using "graph paper" commands to create plots on the screen. There are six different types of "graph paper" from which to choose:

plot linear x-y plot

loglog loglog x-y plot

semilogx semilog x versus y plot

semilogy x versus semilog y plot

ploar polar plot

mesh 3 dimensional mesh surface

Once a plot is on the screen, the plot may be labeled, titled, or have grid lines drawn in:

title plot title

xlabel x-axis label

ylabel y-axis label

text other labels

grid grid lines

Finally, there are commands for screen control, manual axis scaling, and hardcopy on a printer.

shg show graphics screen

cla clear alpha screen

clg clear graphics screen

home home alpha cursos

axis manual axis scaling

hold hold the plot on the screen

print hardcopy

X-Y PLOTS:

The plot command creates linear x-y plots. Once the plot command is understood, logarithmic and polar plots are created by substituting the commands loglog, semilogx, semilogy, or polar for plot. All five commands are used the save way; they only affect how the axis is scaled and the data displayed. If y is a vector, plot(y) produces a linear plot of the elements of y versus the index of the elements of y. for example, suppose we would like to plot the numbers [0., .48, .84, 1., .91, .6, .14]. This is quickly accomplished by typing

y = [0. .48 .84 1. .91 .6 .14];

plot(y)

which results in the graph on your screen

You draw the plot and insert it here

Notice that the data are auto-scaled and x and y axes are drawn. Once the command display has been brought back, by hitting the return key, a graph title, x and y labels, and grid lines can be put on the plot by successively typing the commands

title('my first plot')

xlabel('fortnights')

ylabel('furlongs')

grid

This results in the display:

You draw the plot and insert it here

If x and y are vectors of the same length, the command plot(x,y) draws an x-y plot of the elements of x versus the elements of y. for example, typing

t=0:.05:4*pi;

y=sin(t)

plot(t,y)

results in

You draw the plot and insert it here

Often it is necessary to plot multiple lines on one plot. The command;

plot(x1,y1,x2,y2,....,xn,yn)

will plot x1 versus y1, x2 versus y2, ... xn versus yn on one plot.

SCREEN CONTROL:

PC-MATLAB conceptually has two displays, a graphics display and a command display. Your particular hardware configuration may allow both to be seen simultaneously, or it may allow only one to be seen at a time. Several commands are available to switch back and forth between the displays, and/or erase the displays, as required:

shg show graphics screen

any key show alpha screen

cla clear alpha screen

clg clear graphics screen

home home alpha cursor

For example, if during your PC-MATLAB session only the command display is on the screen, typing shg will rrecall the last plot that was drawn on the graphics display.

LOGRARITHMIC AND PLOAR PLOTS:

Loglog, semilogx, semilogy, and polar are used the same way as the plot command. They allow plotting the data in different coordinate systems.

* Polar(theta,rho) makes a plot using polar coordinates of the angle

theta, in radians, versus the radius rho. Subsequent use of the

grid command draws polar grid lines.

* Loglog makes a plot using log10-log10 scales.

* Semilogx makes a plot using semilog scales. The x-axis is log10

while the y axis is linear.

* Semilogy makes a plot using semilog scales. The y axis is log10

while the x axis is linear.

8 HELP FACILITY:

A HELP facility is available, providing on-line information on most PC-MATLAB topics. To get a list of HELP topics, type

help

To get HELP on a specific topic, type help topic. For example,

help eig

provides HELP information on the use of the eig(envalue) function.

help [

tells how to use brackets to enter matrices.

9 CONTROL SYSTEM TOOLBOX:

PC-MATLAB has a rich collection of functions immediately useful to the control engineer or system theorist. comoles arithmetic, eigenvalues, root finding, matrix inversion, and FFT's are some examples of important numerical tools that are available. More generally, PC-MATLAB's linear algebra, matrix computation, and numerical analysis capabilities provide a reliable foundation for control system engineering as well as many other diciplines. The CONTROL SYSTEM TOOLBOX using PC-MATLAB matrix functions, builds where the foundation leaves off to provide functions specialized to control engineering. The CONTROL SYSTEM TOOLBOX is a collection of algorithms, expressed as .m files, or macros, that implement common control system design, analysis, and modeling techniques. Control systems can be modeled as transfer functions, or in state space form, allowing both classical and modern techniques to be used. Both continuous time and discrete time systems are handled. Conversions between various model representations are provided. Time responses, frequency responses, and root locus measures can be computed and plotted. Other functions allow pole placement, optimal control, and estimation. Finally, and most importantly, tools that aren't found in the toolbox can be created by writing new .m files.

CONVERSIONS BETWEEN STATE SPACE AND TRANSFER FUNCTION FORMS:

[num,den] = ss2tf(a,b,c,d,iu) state space to transfer function

[z,p,k] = ss2zp(a,b,c,d,iu) state space to zero pole

[a,b,c,d] = tf2ss(num,den) transfer function to state space

[z,p,k] = tf2zp(num,den) transfer function to zero pole

[a,b,c,d] = zp2ss(z,p,k) zero pole to state space

[num,den] = zp2tf(z,p,k) zero pole to transfer function

CONVERSIONS BETWEEN CONTINUOUS TIME AND DISCRETE TIME FORMS:

[ad,bd] = c2d(a,b,ts) continuous to discrete time

[a,b] = d2c(ad,bd,ts) discrete to continuous time

OTHER CONVERSIONS:

append append system dynamics

connect system interconnection

parallel parallel system connection

series series system connection

ord2 a,b,c,d for a second order

system

CONTINUOUS TIME ANALYSIS FUNCTIONS:

impulse impulse response

step step response

lsim simulation with arbitrary inputs

bode bode and nichols plots

nyquist nyquist plots

DISCRETE TIME ANALYSIS FUNCTIONS:

dimpulse unit sample response

dstep step response

dlsim simulation with arbitrary inputs

filter SISO z transform simulation

dbode discrete bode plot

freq SISO z transform frequency response

FOR BOTH CONTINUOUS AND DISCRETE TIME:

damp damping factors and natural frequencies

ctrb controllability matrix

obsv observability matrix

tzero transmission zeros

CONTINUOUS AND DISCRETE TIME DESIGN FUNCTIONS:

margin gain and phase margins

place SISO pole placement

rlocus root locus

10 EDLIN LINE EDITOR:

One editor available on the microcomputer network is named EDLIN. EDLIN is a line editor. The editor can be invoked while in PC-MATLAB by entering:

>> !edlin myprog.m

where >> is the PC-MATLAB prompt, the symbol ! tells PC-MATLAB that what follows is a MS-DOS command, and myprog.m is the file that is to be edited. To return back to PC-MATLAB from the EDLIN editor enter;

* e

where * is the EDLIN command mode prompt. EDLIN has two modes, and input mode and a command mode. The prompt for the command mode is * and there is no prompt for the input mode. Upon invocation, EDLIN comes up in the command mode. To get to the insert mode, enter

* i

To return to the command mode from the insert mode enter

ctrl z

A short list of often used commands follows:

COMMAND MODE

*l lists the program

*i switch to insert mode

*e exit the editor (the file is saved

on your floppy disk in drive a)

INSERT MODE

3i insert after line 3

2,4d delete lines 2 thru 4