1 MatLab Help Notes MatLab is a powerful computer language for specialized calculations in engineering and other technical areas. MatLab is similar in structure to other programming languages and is most closely related in syntax to the c language. Its great strength is that it is easily extended so that a user can purchase or create library functions to tailor the language to a particular discipline. MatLab is available in two forms. The student edition (currently V 6.5, Release 13) comes with the Symbolic Math Toolbox and Simulink. (Toolbox is MatLab's name for library). The professional edition is available on the computer network in the labs and it includes the professional edition of the signal processing toolbox, the controls toolbox, and the symbolic math processor. The student version cost about $100 dollars but it is not a stripped down version. It can do everything the professional version can do. What's missing from the student version is the wide array of toolboxes. Additional toolboxes can be purchased for about $30 dollars each and include such things as the Signal Processing Toolbox and the Controls Toolbox which are useful in such courses as EE 310, 311, and 360. MatLab opens with a screen similar to that shown in Figure 1 below. The three windows are called the Launch Pad, Command History, and the Command Window. Figure 1 MatLab's command window and opening screen. The Launch Pad provides access to certain tools and documentation. The Command History window has a complete history of all of the commands that are typed into the command window including a date and time stamp (in green). You can page back through the history and copy commands or double click on any command in the history window to run it again. The Command Window is the main operating window. You use it by typing in commands which Matlab executes when you push Enter.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
1
MatLab Help Notes
MatLab is a powerful computer language for specialized calculations in engineering and
other technical areas. MatLab is similar in structure to other programming languages and
is most closely related in syntax to the c language. Its great strength is that it is easily
extended so that a user can purchase or create library functions to tailor the language to a
particular discipline. MatLab is available in two forms. The student edition (currently V
6.5, Release 13) comes with the Symbolic Math Toolbox and Simulink. (Toolbox is
MatLab's name for library). The professional edition is available on the computer
network in the labs and it includes the professional edition of the signal processing
toolbox, the controls toolbox, and the symbolic math processor. The student version cost
about $100 dollars but it is not a stripped down version. It can do everything the
professional version can do. What's missing from the student version is the wide array of
toolboxes. Additional toolboxes can be purchased for about $30 dollars each and include
such things as the Signal Processing Toolbox and the Controls Toolbox which are useful
in such courses as EE 310, 311, and 360.
MatLab opens with a screen similar to that shown in Figure 1 below. The three windows
are called the Launch Pad, Command History, and the Command Window.
Figure 1
MatLab's command window and opening screen.
The Launch Pad provides access to certain tools and documentation. The Command
History window has a complete history of all of the commands that are typed into the
command window including a date and time stamp (in green). You can page back
through the history and copy commands or double click on any command in the history
window to run it again. The Command Window is the main operating window. You use
it by typing in commands which Matlab executes when you push Enter.
2
The command window is very much like a sophisticated calculator. You may enter
equations and assign values to variables. These are remembered as you proceed down the
sheet. All commands terminate with either a semicolon or the enter key. If you omit the
semicolon, MatLab automatically prints the result of that command to the screen. Thus,
entering 5 + 6; does nothing. But entering 5 + 6 produces the answer 11.
But Matlab is much more than a calculator. It also provides a sophisticated programming
language that lets you enter, edit, and run full programs. These are done in m-files. An
m-file is just a text file that contains a list of instructions similar to what you might type
into the command window. The instructions can have loops, if statements, and functions
and the syntax is very similar to that of a programmable calculator.
For simple calculator-like use you can open Matlab and type in the equations. For
example, if I want to find the arc tangent of 0.5 in degrees, I would enter the following: >> atan(.5)*180/pi
ans =
26.5651
Since all angles are in radians, I multiply by 180o per Pi radians to convert to degrees.
Matlab provides an answer to four decimal places. To get more accuracy in my result I
change the format with a format statement like this: >> format long
>> atan(.5)*180/pi
ans =
26.56505117707799
To write a program as an m-file, I first need to tell Matlab where to store the program. If
you don't do this Matlab stores the program in a default directory. You can change your
default directory in several ways. The quickest way is to just enter the new path as a
change directory command in the command window as you would if you were using
DOS. For example, >> cd c:\courses\ee210
changes the default directory to ee210 under courses on my c: drive. (Other DOS
commands work in the command window as well.) If you don't remember DOS
commands, you can change the current directory with a mouse by clicking on the Browse
button on the current directory list at the top center of the screen. You can also change
the directory by selecting the current directory tab in the Command History window and
browse for a directory there.
After you have a directory established you can create a new m-file by selecting
FileNewM-File from the file menu. Matlab then opens an editor and you are ready
to enter your program. The editor window looks like that shown in Figure 2.
3
Figure 2
The editor window. To open the editor select FileNewM-File from the file menu.
Note that we have not yet named our M-File or saved it. For a simple example enter the
following five lines into your open edit window. %Test.m
x = 3;
y = 92;
z = x^4 - y^2 + 12;
disp(z);
The first line begins with a % sign so it is a comment and is otherwise ignored by the
program. The next three lines create three new variables and assign them values. The
last line displays the value of z. Note that we could have displayed the value of z simply
by omitting the semicolon at the end of the equation for z.
Save your m-file as Test.m and return to the Command Window by selecting it at the
bottom of the screen. In the command window type test to get the result shown below. >> test
-8371
4
Since Test is the name of an m-file in your directory it becomes the name of a command
which can be executed from the command window. Typing the word test causes Matlab
to execute the commands saved in the m-file.
Learning Matlab is a matter of learning the syntax of the language. The language itself is
all command line driven but with a few hours of practice on some examples you can
become relatively proficient. What follows is a list of the more common commands and
some examples of how they might be used in a circuits class.
Getting Help Matlab's help can be frustrating until you learn a few basic commands. But Matlab
provides detailed help on every function and in many cases provides an example of how
the function is used. For example, if I want to know how the roots function is used I enter
the following: >> help roots
Matlab produces the following lines. ROOTS Find polynomial roots.
ROOTS(C) computes the roots of the polynomial whose coefficients
are the elements of the vector C. If C has N+1 components,
the polynomial is C(1)*X^N + ... + C(N)*X + C(N+1).
See also POLY, RESIDUE, FZERO.
The difficulty is that many times you think there ought to be a function but you don't
know its name so you don't know what to ask for help about. When this happens enter
helpwin. The helpwin command provides a hypertext linked help document that allows
you to see all of the functions by category. Enter helpwin into the command window to
get the screen shown in Figure 3.
Figure 3
Enter helpwin to get this screen. Click on any topic in blue for additional information on
that topic. For example click on Elfun to get a list of all of Matlab's elementary math
functions.
5
One other command is useful when you need help. That's the lookfor command. This
command searches through all of the m-files and functions looking for a keyword. For
example lookfor roots produces the following display.
>> lookfor roots
POLY Convert roots to polynomial.
ROOTS Find polynomial roots.
GFROOTS Find roots of a polynomial over a prime Galois field.
RLOCFIND Find root locus gains for a given set of roots.
MROOTS Polynomial roots with multiplicity estimate
vroots.m: % function out = vroots(mat)
FILTCON Returns roots for DFILDEMO.
FILTFUN Returns frequency response and roots for DFILDEMO.
FILTFUN2 Return frequency response norm and roots for DFILDEMO.
POLYSCALE Scale roots of polynomial.
RLOCFIND Find root locus gains for a given set of roots.
RLOCFIND Find root locus gains for a given set of roots.
You can then follow this up with a help on one of the listed commands for more detailed
help. The lookfor command is somewhat of a last resort since it searches all of the m-
files and takes several minutes (or longer) to complete. You can cancel it in mid-flight by
entering Control-C.
Editing and Screen Ops: Here is a list of the more common editing and screen operators and a brief description
of what they do.
quit - exits MatLab. You can also exit from the file menu. exit works as well.
variable names - Variables start with a letter and may be up to 19 characters long.
After the first letter you can use letters, numbers, and underscore. MatLab is
CASE sensitive - nt is a different variable than nT. Note that m-file names are
NOT case sensitive so Test is the same as test.
clear - clear by itself clears ALL variables (without asking). clear x clears only the
value of x.
comments - All text after a % sign is a comment.
; - A semicolon at the end of a line suppresses printing of the results of that line. If
you forget the semicolon your screen rapidly fills up with results you don‟t want.
Multiple commands can be placed on one line if they are separated by a
semicolon.
: - A colon is used to create arrays, address a matrix, or specify iterations. Here are
some examples:
j:k is the same as [j, j+1, ..., k]
j:i:k is the same as [j, j+i, ..., k]
A(:,j) is the jth column of A (read this as all rows in column j)
A(i,:) is the ith row of A (read this as all columns of row i)
A(j:k) is A(j), A(j+1), ... , A(k)
... - Exactly three dots at the end of a line allows you to continue on the next line.
6
who - This command produces a list of variable names that you have used in the
current session. Type the name of the variable to get its value. You can also type
whos to get the variables listed in a long form with more information.
editing -Use the cursor keys (, , , and ) for editing. Push once to see the
previous command or gets the next command (if there was one). Once you have
a command listed you can edit it using and plus the backspace and delete
key. Push enter to re-evaluate the command. You can likewise use the mouse to
scroll backward through the window to view commands that have rolled off the
screen.
save filename - This command saves the current workspace. You should normally
use the .mat extension as in Myfile.mat.
load filename - This command loads a file saved with the save command to restore a
previously saved workspace.
what - Produces a listing of m files, mat files, and mex files in the current directory.
lookfor- searches through help files for a keyword. This is more useful than help
topic since you don‟t have to know the topic name that MatLab uses. The syntax
is: lookfor keyword
For example, lookfor filter, produces 21 entries from which you can ask for syntax
help.
format - using the format command sets the format of the numbers and results
MatLab displays. (The internal representation remains unchanged). The
following are the most useful format commands:
format compact Reduces line spacing in the command window format long 16 digits format short 6 digits (the default) format short e 6 digits with exponent format hex hexadecimal
M Files The real power of MatLab comes from the ability to create programs which can be
saved and executed from the command window. MatLab programs are called m-files.
To write an m-file you should first change MatLab's directory to the disk location
where you want to store the m-file. Use the cd command to change the directory from
the command window. If you want to know what directory you are in use the pwd
command.
M files are also referred to as “script files”. An m-file is a text file that contains
statements executable by MatLab. M-files are stored on your computers disk and
have a name of the form “filename.m”. They are executed in MatLab by typing the
filename (without the extension) at the MatLab prompt in the command window.
Execution of an m-file produces the same results as if you had typed the information
in one line at a time. M-files represent a very powerful way to extend the MatLab
command language.
7
M File Manipulation:
dir - This is the same as the DOS command for directory. ls works as well.
cd - This is the same as the DOS command for change directory.
type filename - looks for the file called filename.m in the current directory and
displays it in the command window.
delete filename - deletes filename.m in the current directory.
pwd - same as the UNIX command for print working directory. Typing cd alone
(without a path) produces the same result in MatLab.
which filename - displays the path to filename.m
Creating M Files:
You can create an m-file using any word processor or editor that will create a text
(ascii) file with a .m extension. In DOS it is convenient to use EDIT but a full
word processor offers more text manipulation options. MatLab has it‟s own built
in editor which you can invoke from the file menu in the command window.
From the File menu in the command window select new m-file. You will see the
following screen shown in Figure 2. This is MatLab's m-file editor.
Here is an example of an m-file named Sineplot which produces a plot of sin(x)
and cos(x) using the plot function. Because MatLab is somewhat arcane in its
syntax, m-files should be fully commented.
% TITLE: Sineplot.m
%
% This m file creates a plot of sin(x) and cos(x) using
% the plot function.
%
x = (-4*pi:pi/100:4*pi); % x goes from -4Pi to 4Pi
y1 = sin(x); % y1 is the sin(x)
y2 = cos(x); % y2 is the cos(x)
figure(1); % Select figure 1
clf; % Clear the figure
plot(x,y1,'blue'); % Plot sin(x) in blue
hold on; % keep it from being erased
plot(x,y2,'red'); % Plot cos(x) in red
Figure 4 An example MatLab m-file which creates a plot of sin(x) and cos(x) for x going
from -4 to +4
You may type in the program in Figure 4 using MatLab's editor. Save the file
under the name sineplot.m. Return to the command window and run the
program by typing sineplot. If all goes well you should get the results shown
in Figure 5 below.
8
Figure 5 The results of running the program called sineplot shown in Figure 4.
Matrix (Array) Ops and Definition Array - MatLab commonly uses the word Array to mean a one dimensional matrix.
When an array has more than one dimension it is referred to as a matrix.
Addressing an array -
x(3) is the third element of x.
x(1:3) is elements 1, 2, and 3 of array x.
x(1:2:4) is elements 1 and 3. In this notation 1 is the starting value, 2 is the step
size, and 4 is the last value - x(Start:Step:End).
Creating an array - MatLab does not contain a dimension statement or any other
explicit way to declare a variable and its size. Variables are dimensioned as
needed. This sometimes causes problems when a matrix used in one part of a
program needs to be made larger in a second part. You can get around this by
creating and sizing a vector at the outset by using the zeros command.
zeros - This command produces zeros an assigns them to a variable or an array.
The syntax is x = zeros(size);
where size is the dimensions of x. For example x = zeros(3,5); creates x
as having 3 rows and 5 columns and initializes them to zero.
ones - This command is the same as the zeros command except that it produces
arrays of ones.
Array Creation Examples
Create an array, x, with four elements. Note the use of the square bracket [ ]. x = [1 2 3 4];
x is a 1 x 4 row matrix. To create a column matrix write:
9
x = [1;2;3;4]; or x = (1;2;3;4);
or, use the transpose operator (see below).
Create a second array, y, where each element is the square root of the elements
in x array. y = sqrt(x);
Create a third array, z, where each element is 2 times the element in x. z = 2*x;
Create an array using colon notation. In this example x is an array having
elements 0, 2, 4, 6, 8, and 10. The format is x(Start, Step, End). If
you leave out the step value, it defaults to 1. x = [0:2:10];
Create an array by combining two other arrays. In this example A has three
elements and B has 4 elements. A new array, C, is made by combining A
and B. In combining two arrays you use [ ]. A = (1:3); B = (4:7);
C = [A B];
C will consist of elements 1 2 3 4 5 6 7
Create an array using the linspace or logspace commands. These operators
creates a linear or log space between two specified end points. The syntax
is: x = linspace(start, last, number);
x = logspace(start, last, number);
Matrix Arithmetic
Addition, subtraction, multiplication, and division are defined in two ways for
arrays and matrices. The operators normally used (+, -, *, and /) are defined as
they usually are for matrices (division of two matrices is defined as
multiplication by the inverse). The operators of multiplication and division
are also defined using the dot notation (.*, and ./) to mean that the operations
are to be performed on an element by element basis.
Operations between a scalar and an array are done to every element in the array.
For example C = A - 2; will subtract 2 from every element in A and make
the new matrix C.
Transpose - use the .' operator. For example if B is a row matrix (say 1 x 5) then
writing C = B.' would make C a column matrix (5 x 1). The dot apostrophe
is necessary for a transpose. Using the apostrophe alone does a complex
conjugate transpose.
Solving Simultaneous Equations MatLab makes solving simultaneous linear equations very easy since it is very good at
manipulating matrix equations. Consider the set of equations given below.
1254
1362
733
32
31
321
xx
xx
xxx
In these three equations, x1, x2, and x3 are unknown. We can rewrite these equations
in matrix form as bxA
10
where the three matrices A, x, and b are given by
540
602
331
A
12
13
7
b
3
2
1
x
x
x
x
Since Matrix division is not defined we solve the matrix equation for x as
bAx 1
where the term 1A is defined as the matrix inverse of A.
Thus, to solve these three equations, we need only find the inverse of the A matrix
and multiply it times the b matrix. In MatLab we write the following three lines. A = [1,3,3;2,0,-6;0,4,5];
b = [7;-13;12];
x = A^(-1)*b
Leaving the semicolon off of the last line causes MatLab to print the value of x as x =
-0.5000
0.5000
2.0000
Output and Input Printed output:
To print the value of any variable in the workspace. simply type the variable name
followed by the enter key. You can use format compact to get a neater
display. The result of any equation in the workspace or in an m-file will be
printed to the screen if you leave off the semicolon at the end of the line.
disp – display. This is the same as leaving the semicolon off of an expression. It
allows a little more clarity in programs.
fprintf - prints formatted data to a file or to the screen. The syntax is fprintf(fid, 'format string', arg1, arg2, ... );
The format string contains conversion characters that determine how the output is
printed. Each conversion character must be preceded by a percent sign (%).
Adding a \n to the format string produces a new line. The common conversion
characters are: c single character d signed integer e floating point with an exponent f floating point without an exponent g general format. Uses e or f as needed. i signed integer o octal integer s string u unsigned integer x hexadecimal integer
11
The term fid is a file identifier. If fid = 1 the output is sent to the screen.
This is similar to the command for formatted output in C (printf). Here are
few examples. i = 13; j = -45; r = 39.567; s = 5.4136789;
This is all one figure in Matlab but the figure has 2 rows and 1 column of subplots. The
top subplot shows the capacitor voltage vs time while the bottom subplot shows the
capacitor current vs. time.
28
Example 3 – Complex Impedances Use Matlab to evaluate the complex impedance between terminals A and B in the circuit
of Figure E3-1.
Figure E3-1
Find the equivalent complex impedance between terminals A and B.
In Matlab any variable can be real, imaginary, or complex and it can be a simple variable
or it can be a matrix. There is no special designation for these different form of variables
and they need not be explicitly declared.
For this example we will call the impedance of L1 by the variable name Z1. In Matlab
we write Z1 = j*5;
Matlab recognizes j as 1 but the multiplication sign must be added in explicitly. You
can also use i as 1 as is done in physics and mathematics. In electrical engineering i
usually stands for current and j is taken as the imaginary number 1 . Note that if, in
your program you define either i or j to be something else, such as by using i as a loop
counter in a for loop, you can no longer use it as 1 .
The series combination of R1 and L2 will be called Z2. In Matlab this is written as Z2 = 5 + j*8.66;
The parallel combination of R2 and C1 will be called Z3. In Matlab we can write this as Z3 = (15*(-j*10))/(15-j*10);
The equivalent impedance at terminals A and B is then the parallel combination of Z1,
Z2, and Z3. In Matlab we write Zab = (Z1*Z2*Z3)/(Z1*Z2+Z1*Z3+Z2*Z3);
An m-file called Example3.m is shown in Figure E3-2 which implements these equations
and displays the results. The m-file also shows how to use the abs, angle, real, and imag
functions.
29
%Example3.m
Z1 = j*5;
Z2 = 5 + j*8.66;
Z3 = (15*(-j*10))/(15-j*10);
Zab = (Z1*Z2*Z3)/(Z1*Z2+Z1*Z3+Z2*Z3);
rab = abs(Zab); %Value of r
thetaab = angle(Zab)*180/pi; %Value of theta in degrees
realZab = real(Zab); %Real part
imagZab = imag(Zab); %Imaginary part
%Use the disp function to show the results
disp('The value of Zab is ');
disp(Zab);
disp('The magnitude of Zab is ');
disp(rab);
disp('The angle of Zab in degrees is ');
disp(thetaab);
disp('The real part of Zab is ');
disp(realZab);
disp('The imaginary part of Zab is ');
disp(imagZab);
Figure E3-2 An m-file to calculate the complex impedance for the circuit of Figure E3-1.
30
Example 4 – Printing and Plotting Matlab provides numerous print and plot options. This example illustrates the basics and
provides enough detail that you can use it for typical classroom work and assignments.
Printing Figures
Using the command print by itself either from the command line or in an m-file causes
the current figure to be sent to the printer. If there are multiple figures, you can designate
a figure number in an argument. For example print(2); will print figure 2 even if
figure 1 is the current figure. There are numerous formatting options including options
that allow you to print a figure to a file as a jpg image. See help print for details. For
classroom purposes, what is generally needed is a way to put a figure into a document.
You can do this easily by choosing EditCopy Figure from the menu on the current
figure. This option copies the current figure to the clipboard. You can then open Word
and use EditPaste to past the figure into the Word document. Word has easy to use
commands to let you resize and center the figure on your page. All of the figures in the
help files were pasted in from Matlab using this technique.
One other alternative is to push the Print Screen button on the keyboard when you have a
Matlab figure on the screen. This command copies the entire screen to the clipboard.
You can then use Paint (from the accessories menu in Windows) and past the screen
image into Paint. Paint has many options to allow you to clip out portions of an image or
to add in other images or text. Once the figure is in paint it is easy to select the figure or a
part of it and copy it to Word for further text documentation.
Printing Results
One of the frustrating things about Matlab is getting it to print your results to the screen in
some specified format. Matlab uses the old c-style print commands and the formatting
options are hard to remember if you don‟t use them often.
Any expression in Matlab which does not end in a semicolon will print results to the
screen. Thus if I enter y = 5 + 7 in an m-file or the command line I get the following: >> y = 5 + 7
y =
12
whereas if I terminate the expression with a semicolon, the printed output is suppressed.
Matlab also has a display function called disp. The disp function is similar to omitting
the semicolon but printing is a bit more explicit and Matlab produces fewer blank lines in
the output. For example, here's how to print the value of y in the problem above using
disp. >> y = 5 + 7;
>> disp(y);
12
31
While the disp function does a little better job than just omitting a semicolon, the output
is not formatted and you can not display multiple items on one line. To do that you have
to use the fprintf function.
The fprintf function has the following format. fprintf(fid, format string, variable, variable, ... );
In this format, fid is file ID field. For the screen, set fid to 1 or omit it completely. The
format string is a Matlab string enclosed in single quotes that specifies the format of the
output. The variables may be in a matrix or they may be single variables separated by
commas. If the variables are in a matrix they are printed by rows.
The format string contains conversion characters that determine how the output is printed.
Each conversion character must be preceded by a percent sign (%). Adding a \n to the
format string produces a new line. The common conversion characters are:
c single character d signed integer e floating point with an exponent f floating point without an exponent g general format. Uses e or f as needed. i signed integer o octal integer s string u unsigned integer x hexadecimal integer
Figure E4-1 Format characters for the fprintf command in Matlab.
This is similar to the command for formatted output in C (printf) and you can look up
more details about the print format in a C manual. Here are few examples. i = 13; j = -45; r = 39.567; s = 5.4136789;