Sei sulla pagina 1di 32

ME365 MATLAB Introduction Notes

MATLAB INSTRUCTIONS FOR ME 365

(Updated: Fall 2004)

This document is a much shortened version of the instruction set for MATLAB.
It is intended to help you get started. Once you know the basics, the MATLAB help function can
be used to help you learn the commands and how to run them. I like the student version manual,
because it has examples that are helpful.

-1-
ME365 MATLAB Introduction Notes

TABLE OF CONTENTS

A. The Preliminaries.......................................................................................................... 3
A.1 Computer Setup for MATLAB.................................................................................... 3
A.2 Unix commands while running MATLAB on a UNIX machine. .................................. 4
A.3. Some very basic commands. ................................................................................... 5
A.4 Getting Help .............................................................................................................. 7
A.5 Creating an M-file...................................................................................................... 9
A.6 Plotting a graph on the screen ................................................................................ 11
A.7 Sending the plot to the printer. ................................................................................ 13
A.10 Loading Data......................................................................................................... 14

B. Some Examples of Things You May Do. ................................................................. 16


B.1 Entering Data and Plotting it.................................................................................... 16
B.2 The Dreaded "dot" Command, Subtitled: Loops Without Loops!............................. 18
B.3 Calculating and Plotting a Step Response. ............................................................. 21
B.4 Calculating an Plotting a Frequency Response Function........................................ 22

C. A Little More Sophistication in MATLAB Programming.......................................... 25


C.1 Loops in a Fourier Series Example ......................................................................... 25
C.2 If Statements........................................................................................................... 27
C.3 While Statements.................................................................................................... 27
C.4 Subroutines/Functions ............................................................................................ 28
C.5 Changing graph font sizes and line thickness, etc. ................................................ 29

-2-
ME365 MATLAB Introduction Notes

A. The Preliminaries

On the PC's the basic commands like plotting, printing and editing are found in the menus that
come up after you have launched MATLAB.

A.1 Computer Setup for MATLAB

First lets deal with the Computers running under the UNIX operating system. You should be in an
X-windows environment when you initiate MATLAB. At the prompt, you just type:

matlab

and the computer will initiate the program. By default this generates a window (desktop) similar to
the one that you are in when you launch MATLAB on a PC. The Command Window part of this
desktop is where you type in your commands. You will see a prompt: >>, in the window. You can
turn off the various elements of the desktop, as you wish. If you like to stay in a more UNIX-style
environment, you can, instead, type:

matlab -nodesktop

at the prompt, and you will stay in your current X-window and a >> prompt will appear. To leave
MATLAB just type:

>>quit

in the Command Window (or the X-Window if there is no desktop window) and all the associated
MATLAB generated windows will disappear.

On the PCs you need to find the Applications folder and in there you will see the MATLAB icon.
Double click on this to launch MATLAB. It'll take a short while before a command window will
pop up. To leave MATLAB pull down the menu and find the command that says EXIT MATLAB
or just type:

>>quit

-3-
ME365 MATLAB Introduction Notes

A.2 Unix commands while running MATLAB on a UNIX machine.

Once you are running MATLAB in a UNIX environment, you can still use UNIX commands, so
long as you put an exclamation mark before the command. So, for example, if you wanted to find
the time and date, date is a UNIX command that gives you this information. In MATLAB type:

>>!date

and the UNIX command will be executed. If you are using the –nodesktop option, you can use the
simple vi editor, by typing:

>>!vi john.m

and this will allow you to create or update the file called john.m. When you type the :wq command
to save and come out of the editor, you will find yourself back in MATLAB. Alternatively, and
more convenient when developing programs (m-files), you can do your editing from another
window. If you are using the –desktop option (the default), you can use the inbuilt MATLAB
editor (you’ll find it in one of the pull-down menus) or again, do your editing outside MATLAB in
another application window. If you type

>>!ls
or
>>ls

you should see john.m and all the other files in that directory.

Program files in MATLAB always have a ".m" extension. MATLAB looks for these m-files in the
directory you are working in, when you type a command from within MATLAB. MATLAB also
looks in its own directories for the command. Where MATLAB looks is stored in the path variable.
You can extend the list of directories in which MATLAB looks for commands in by using the path
command. Normally you will not be doing this in the UNIX environment because you are working
in the directory where the files are kept. On the PCs, you will use this command to tell MATLAB
to look on the floppy disk drive or on the drive connected to your ecn account.

-4-
ME365 MATLAB Introduction Notes

A.3. Some very basic commands.


MATLAB is happy to have variables that are scalars, vectors or matrices and it is easy for you to
create them without having to declare data types as you do in C or Fortran. MATLAB can also
interpret complex numbers and will do complex arithmetic. It will also do matrix algebra for you,
so long as you have the correct dimensions for the vectors and matrices, and it will also solve sets
of equations for you. As an example, suppose we have a set of three linear equations in matrix
form:

[A] x = b.,

⎡1 1 1⎤ ⎡6⎤
where [A] = ⎢1 2 3⎥ , and b = ⎢⎢14 ⎥⎥ ,
⎢ ⎥
⎢⎣1 4 9⎥⎦ ⎢⎣36⎥⎦
and we wish to solve for x. To do this we type:

>>A=[ 1 1 1;1 2 3;1 4 9 ];


>>b=[ 6 14 36 ]';
>>x=A\b;
>>x'

which prints the result as a row vector. Note the use of the semicolon at the end of the commands;
this suppresses output to the screen. Within the matrix specification, the semicolon is used to
denotes “next line” of the matrix. The accent ' denotes transpose. . x and b are column vectors, but
in this example it is easier to input and display them as row vectors. The square brackets are used
to input vectors and matrices. The \ operator in the A\b command tells MATLAB to solve the set of
equations [A] x = b.

Let's look at another example. Suppose we have a function defined by:

−2 x
y = 24e + 4,

and we wish to plot it for from x = −5 to x = 15. Let’s plot it with x incrementing in steps of 0.1 as
it goes from −5 to15. Suppose we also wish to label axes and put a title on the plot. To do this, you
type in the following commands:

>>x=(-5:0.1:15);
>>y=24*exp(-2*x)+4;
>>plot(x,y)
>>xlabel(‘Distance (x) – Kilometers’)
>>ylabel(‘Number of Complaints’)
>>title(‘Community Response Model’)

-5-
ME365 MATLAB Introduction Notes

After typing these commands the plot will appear in a window on your screen. The plot will look
like the one in the Figure below.

5 Community Response Model


x 10
6

4
Number of Complaints

0
−5 0 5 10 15
Distance (x) − Kilometers

Figure 1: Example output of plotting a function.

To save plots you can export them to a file using the export option in the menus associated with
the plot. Be careful about exporting to .eps files because you cannot always preview the plot in MS
Word and PowerPoint file. I most often export to a .jpeg file but it does not always give good
enough resolution. You can save the plot to a postscript file with preview capabilities by using the
print command in the command window with the –tiff option turned on. It’ll save the latest plot
that you made.

>>print –depsc2 –tiff Figure1

saves the plot in Figure1.eps.

You can also change the resolution by using the –r flag with this print command, type help print to
see a full explanation of all the options. This figure was inserted into this document by selecting
the INSERT PICTURE FROM FILE sequence, and then browsing for Figure1.eps.

-6-
ME365 MATLAB Introduction Notes

Note that if you had wanted to do the calculations to make this plot in a Fortran or a C program,
you would have had to use a loop. Here MATLAB automatically calculates y for each value of x.
Although, not apparent to you, x is actually a row vector with 201 values in it. You can check this
by typing:

>>size(x)

y is also a 201 length row vector generated by taking each element of x and performing the
calculation in the command line. You can print out the first five elements of y by typing:

>>y(1:5)

Another useful command is whos which results in a listing of all the variables in use, and the size
and type of the variables. This is useful if you have made a programming error because you can
immediately see that vectors and matrices are not the size you expected them to be.

A.4 Getting Help


MATLAB has a good online help facility. When you want to find out how a function works you
just type help followed by the name of the function. For example, suppose you wanted to know
how the function plot works, you just type:

>>help plot

and then the following information will appear on the screen.

PLOT Linear plot.


PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix,
then the vector is plotted versus the rows or columns of the matrix,
whichever line up.

PLOT(Y) plots the columns of Y versus their index.


If Y is complex, PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)).
In all other uses of PLOT, the imaginary part is ignored.

Various line types, plot symbols and colors may be obtained with
PLOT(X,Y,S) where S is a character string made from one element
from any or all the following 3 colunms:

-7-
ME365 MATLAB Introduction Notes

y yellow . point - solid


m magenta o circle : dotted
c cyan x x-mark -. dashdot
r red + plus -- dashed
g green * star
b blue s square
w white d diamond
k black v triangle(down)
^ triangle(up)
< triangle(left)
> triangle(right)
p pentagram
h hexagram

For example, PLOT(X,Y,'c+:') plots a cyan dotted line with a plus


at each data point; PLOT(X,Y,'bd') plots blue diamond at each data
point but does not draw any line.

PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots defined by


the (X,Y,S) triples, where the X's and Y's are vectors or matrices
and the S's are strings.

For example, PLOT(X,Y,'y-',X,Y,'go') plots the data twice, with a


solid yellow line interpolating green circles at the data points.

The PLOT command, if no color is specified, makes automatic use of


the colors specified by the axes ColorOrder property. The default
ColorOrder is listed in the table above for color systems where the
default is yellow for one line, and for multiple lines, to cycle
through the first six colors in the table. For monochrome systems,
PLOT cycles over the axes LineStyleOrder property.

PLOT returns a column vector of handles to LINE objects, one


handle per line.

The X,Y pairs, or X,Y,S triples, can be followed by


parameter/value pairs to specify additional properties
of the lines.

See also SEMILOGX, SEMILOGY, LOGLOG, GRID, CLF, CLC, TITLE,


XLABEL, YLABEL, AXIS, AXES, HOLD, COLORDEF, and SUBPLOT.

Another useful command is the diary command. After you type this command, everything that
appears in the command window will appear in a file called diary. This will stop when you type:

>>diary off

This is useful when you want to put part of the help in a file, or if you want to record the results of
your analysis. You can change the file name in which the diary is stored by typing the desired

-8-
ME365 MATLAB Introduction Notes

filename after the diary command. Below is a sequence of commands to record the results of your
analysis performed by the commands in an m-file (see next section) called john.m. The results will
be stored in the file myresults.

>>diary myresults
>>john
>>diary off

A.5 Creating an M-file.


If you wish to redo a command in MATLAB, you can use the arrow keys to move up and down
your current list of commands. You can edit the command and then press return to send it. When
you wish to send a sequence of commands, it is usually best to put these commands together in a
file, then execute the file. That way, if you make a mistake, you can quickly edit the file and
execute it again. This is much more straightforward than rerunning all the commands line by line.
At the end of the day, you also have a file that works that you can refer back to should the need
arise. The file that contains the list of commands is a MATLAB program. These are called m-files
because we always give them an extension ".m". That way, you always know which files are
MATLAB programs.

To create an m-file on the PC you use the EDIT menu command, select NEW and the M- FILE
option. Use the command OPEN if the file already exists and you wish to modify it. You will want
to save the m-file on your floppy drive, so that you can take it away with you, or you can save it in
your ecn account. Don't forget to give the file a ".m" extension. To run the m-file you will need to
include the floppy disk drive (A:) or your ecn account drive (it is always the R: drive on my
computer, might be different for you) in MATLAB's path. To add directions to a drive Q: type:

>>p=path;

which copies the current path into variable p, then type:

.>>path('Q:',p); %Adds main directory in drive Q: to path

or

>>path('Q:\me365dir',p);

which includes directions to the directory (folder) me365dir on the Q: drive in the MATLAB path.

To create an m-file in a UNIX environment, if you are in the desktop environment, it is more or
less the same as on the PC. If you are in the nodesktop environment just use the vi (or other UNIX)
editor in the MATLAB window or open another window (editor) and do your editing from there.
So, for example, if you are going to create john.m and you are in the nodesktop environment, just
type:

>>!vi john.m

-9-
ME365 MATLAB Introduction Notes

which will put you into the editor. When you save and exit the editor you will be back in
MATLAB.

In the MATLAB m-file that you are creating, just type the commands you would have done in the
command window. To put in comments use the % symbol. A good policy is to put the name of the
file and a brief explanation of its functionality at the top of your program, along with your name.
When you print it out, you'll be certain that the printout is indeed your own m-file. Below is an
example of an m-file’s contents; this m-file contains the instructions to sample and plot a function.

%test.m
%Plots a simple function. P.Davies, 08/22/04
%
t=(0:100)/1000; %Generates a time vector 0 to 0.1 seconds.
x=3*sin(40*pi*t); %Uses the time vector to create a 20 Hz sinewave
subplot(211) % Will plot in the upper half of the page
plot(t,x)
xlabel('t-values')
ylabel('x-values')
title('A Simple Matlab m-file Example')

To run this program all you do is type the name of the m-file.

>>test

and the graph will appear in a figure window on the screen, so long as you remembered to set the
path correctly. If you move to work in the directory where you are saving the m-files, you don’t
have to reset the path. MATLAB always looks for programs (m-files) in the directory (folder) in
which you are working. To move to the folder myme365 on the D: drive, type

>>cd D:\myme365

- 10 -
ME365 MATLAB Introduction Notes

A.6 Plotting a graph on the screen

In the examples so far we have already seen the plot command. In fact, we have used the help
facility to print out the explanation as to how plot works. Around the plot commands are other
commands that allow you to plot several plots on one page (subplot), to label axes (xlabel, ylabel),
to put a title on the plot (title), to put annotation on the graph (gtext), to preset axes (axis) and to
clear the figure (clf).

There are other graphing programs, similar to plot, that allow you to make a wide variety of graphs
(stem, semilogx, semilogy and loglog). When you plot frequency response functions you usually
plot them on a logarithmic frequency axis, so you use semilogx instead of plot to plot the
magnitude or the phase of the frequency response function versus frequency. We'll use stem when
we plot Fourier series coefficients. Use the help facility to see how these functions work.

Below is an m-file that will plot the magnitude and phase of a complex function of frequency f:

x = 3( j 2πf + 200 ) .

For the plot the magnitude is converted to decibels and the phase is converted to degrees. Note that
MATLAB understands that j means − 1 , so long as j is not used as another variable within the m-
file. You can also use i in this manner.

% freq.m program to plot magnitude and phase of a complex function


% August 2004, J. Bolander
%
% frequency(f) ranges from 0.1 to 100 in steps of 0.1Hz.
f=(1:1000)/10;
% create x from f
x=3*(j*2*pi*f+200);
%
% Now plot magnitude in decibels on the top half of the page
subplot(211)
plot(f,20*log10(abs(x)))
xlabel('Frequency - Hz.')
ylabel('Magnitude - dB')
%
% Now plot phase in degrees on the bottom half of the page
subplot(212)
plot(f,angle(x)*180/pi)
xlabel('Frequency - Hz.')
ylabel('Phase - degrees')

This creates the plot shown on the next page.

- 11 -
ME365 MATLAB Introduction Notes

66

64
Magnitude − dB

62

60

58

56

54
0 10 20 30 40 50 60 70 80 90 100
Frequency − Hz.

80

60
Phase − degrees

40

20

0
0 10 20 30 40 50 60 70 80 90 100
Frequency − Hz.

Figure 2: Result of plotting a simple complex function of frequency.

There are also three dimensional plotting functions that we will not use in this course, but you may
want to use in other courses (mesh, plot3, surf, stem3).

- 12 -
ME365 MATLAB Introduction Notes

A.7 Sending the plot to the printer.

Having edited and run your m-file until you got the output you expected to see, you are now ready
to send the plot to the printer. One option is to bring down the menu on the plot and find print. In
the UNIX environment, you can also use the print command to send the plot directly to the printer.
Back in the command window type:

>>print –Pml3

This is assuming that the printer name is ml3. Just substitute the name of the printer for which you
have access.

It is possible to put plots in different figure windows, by using the figure command:

>> figure(1)
>> plot(x,y)
>> figure(2)
>> plot(y,z)

If you don't direct MATLAB to a particular figure it will print out the last one you plotted when
you use the print command. To return to a particular figure window, say, for example, the first
figure window just type

>> figure(1)

and when you use the print command now, it’ll print out or save the plot shown in the first figure
window.

As noted above and repeated here for convenience, to save plots you can export them to a file using
the “export” option in the menus associated with the plot. Be careful about exporting to .eps files
because you cannot always preview the plot in MS Word and PowerPoint file. You can save the
plot to a postscript file with preview capabilities by using the print command in the command
window. It’ll save the plots in the figure window that you last talked to.

>>print –depsc2 –tiff Myplot

saves the plot in Myplot.eps, and the –tiff flag sets the preview capability. For more information on
the various options when saving to a file, type help print. Another format I often use are jpeg files.
For that you would type:

>>print –djpeg Myplot

which will create Myplot.jpg. As mentioned above, you can vary the resolution of the saved plot;
this is described when you type help print.

- 13 -
ME365 MATLAB Introduction Notes

A.8 Printing out your m-file.


In the UNIX environment just use the unix command lp.

>>!lp -dml3 -o nobanner test.m

On the PCs open the m-file and select the print command.

A.9 Saving Data


If you have to leave you can save everything in your work space by using the save command. If
you want to save it in a file called home2 you type:

>>save home2

In your directory, you will now see a file home2.mat. You can use the save command to save only
selected variables, if you wish. Normally MATLAB saves them in binary format and in a file with
a .mat extension. You will not be able to read the files, except by loading them back into
MATLAB. To save them in a readable format you use the -ascii option. save does not put a .mat
extension on the ascii file. This is useful when you want to put the numbers calculated in MATLAB
in a table in a report.

A.10 Loading Data.


If you saved your workspace and wish to load it back it because you wish to continue your analysis
just type:

>>load home2
All the variables will have the same names as when you saved the workspace. To see what
variables you have and their dimensions, you can type:

>>whos

To load in ascii data from a file you have created from the editor, from LABVIEW or from another
software package you can type:

>> load fname.ext –ascii

where fname.ext is the filename with its extension. The variable that contains the data will be called
fname in MATLAB, a little confusing! MATLAB will drop the extension, if the filename has one.
In fact, it is easier to change the variable name in MATLAB if you have ascii data files without
extensions. Then you can use the following commands to input the data into your m-file. The input
command is used here so that the user can specify what file to load in at the time of execution of
the program (m-file), i.e., it makes the m-file interactive. eval is a useful function that allows us to
construct commands from variables.

- 14 -
ME365 MATLAB Introduction Notes

% test.m mfile to load in an ascii data file (no extension)


% and load it into the variable a. 08/23/2004, A.Student.
%
%fi is a variable that holds the filename.
fi=input('Filename to load','s')
eval(['load ',fi,';'])
%
%Now copy the data referred to by the filename into the array a.
eval(['a = ',fi,';'])
%
% now lets get rid of the array that has the same name as the
% filename.
eval(['clear ',fi,';'])
%
%now we can do our calculations with the variable a, which
% contains the data we loaded in, e.g.,
y = 2*cos(2*pi*a);
subplot(211)
plot(a,y)

- 15 -
ME365 MATLAB Introduction Notes

B. Some Examples of Things You May Do.


B.1 Entering Data and Plotting it.
Suppose that we have done a static calibration on a temperature transducer and we have actual
temperatures (°C) and measured voltages (V), as shown in the Table 1. Let’s get MATLAB to plot
this. If we have the ascii files of temperature and voltage, we can use the example at the end of the
last section to load the data. Let’s assume here that we have recorded by hand.

Table1: Sample static calibration data for a temperature transducer.


Temperature 0 10 20 30 40 50
Voltage -2.00 -1.51 -1.04 -0.59 0.16 0.25
Temperature 60 70 80 90 100 60
Voltage 0.64 1.01 1.36 1.69 2.00 0.64

An m-file to plot this data would look like:

%calib.m program to plot the temperature calibration data


% October 2001, J. Bloggs.
temp=[0 10 20 30 40 50 60 70 80 90 100];
volt=[-2.00 -1.51 -1.04 -0.59 -0.16 0.25 0.64 1.01 1.36 1.69 2.00];
subplot(211)
plot(temp,volt,'+')
xlabel('Temperature - degrees C')
ylabel('Measured Voltage - V')
title('Static Calibration of a Thermocouple')

To include a straight line fit to the data, we can use the MATLAB program regress. To do this we
have to create a matrix, [X], that has the form:
⎡1 temp1 ⎤
⎢1 temp 2 ⎥
⎢ ⎥,
⎢... ....... ⎥
⎢ ⎥
⎣ 1 temp11⎦
which can specified in MATLAB with:

X = [ones(length(temp),1) temp'];

and a vector, y, that is the vector of voltages transposed into a column vector:

y= volt';

The program regress then finds the coefficients by solving: [X] b = y in a least squares sense. The
coefficients arein the vector b. The program regress also calculatates confidence intervals for the
estimates and for the error (difference between the data and the straight line predicted by the
estimated model), as well as some other statistics such as the coefficient of determination which is

- 16 -
ME365 MATLAB Introduction Notes

commonly referred to as the R2 value. Type help regress, for more detail. Here is what the m-file
would look like including the straight line fit. In this program the R2 statistic is stored in stats(1),
and the confidence intervals for the intercept and gradient are in bin(1,1:2) and bin(2,1:2),
respectively.

%calib.m program to plot the temperature calibration data


% October 1995, J. Bloggs.
temp=[0 10 20 30 40 50 60 70 80 90 100];
volt=[-2.00 -1.51 -1.04 -0.59 -0.16 0.25 0.64 1.01 1.36 1.69 2.00];
%
% Set up the data for regress
y=volt';
X=[ones(11,1) temp'];
alpha=0.01; %for 99% confidence intervals
%
% Now calculate the straight line coeficients, confidence intervals
% and statistics.
[b,bin,r,rint,stats] = regress(y,X,alpha);
%
%Now calculate the straight line model prediction.
yhat=X*b;
%
%Plot the original data and the straight line fit.
subplot(211)
plot(temp,volt,'+',temp,yhat,'-')
xlabel('Temperature - degrees C')
ylabel('Measured Voltage - V')
title('Static Calibration of a Thermocouple')
print -depsc2 -tiff Figure3

The plot that comes from this m-file is shown below.


Static Calibration of a Thermocouple
3
Measured Voltage − V

−1

−2
0 10 20 30 40 50 60 70 80 90 100
Temperature − degrees C

Figure 3: Static calibration data (+) and the result of a straight line fit to the data.

The intercept (bias) was estimated to be –1.850 ± 0.358 volts and the gradient (sensitivity) was estimated to
be 0.0400 0.0061 Volts/°C. Both are 99% confidence intervals; this was specified by setting the parameter
alpha in the regress command to (100-99)/100 = 0.01.

- 17 -
ME365 MATLAB Introduction Notes

B.2 The Dreaded "dot" Command, Subtitled: Loops Without Loops!


As was stated earlier, MATLAB will do matrix arithmetic. It will also perform a calculation on
each element of a matrix. However, you need to be able to tell MATLAB when you want to do
element by element calculations, rather than an operation on the whole matrix. To make MATLAB
do this we use a dot "." in front of the arithmetic function (×,/,−,+). If you miss out these dots then
MATLAB will usually complain, because it tries to do matrix algebra and finds that the dimensions
of the vectors and matrices do not agree. So when you get an error about dimension, it’s usually
because you missed out a dot. A more elusive error to track down is when miraculously the
dimensions do agree and MATLAB performs the matrix algebra, which was not what you wanted.
That is often more tricky to track down because it works but the answer doesn’t make sense and
usually the result is a vector of a different length to what it was expected to be. The whos is useful
for tracking this down. It tells you which variables are in the workspace, their type and their
dimension.

In Fortran or C, you would do these element by element calculations in loops, which takes several
lines of code. In MATLAB you can do the same calculations in a one-line command. Suppose that
we wish to calculate K/(1+jat), for fixed values of t and K and for a set of values of a (the
frequency) from 0.0 to 1000 in steps of 0.5 rad/s. We then want to plot the magnitude (in dB)
versus frequency, and the phase (in degrees) versus frequency. An m-file to do this is shown below.

%fig4.m example to demonstrate the use of the dot command.


% August 2004, Jay Lee.
K=10.;
t=0.01;
a=(0.0:0.5:1000);
y=K./(1+j*a*t);
%
%Note the dot before the divide (/) command, that says do an
%element by element calculation. No need for dots before the
%multiply (*) as MATLAB is happy multiplying vectors and
%matrices by constants.
%
% Now plot the magnitude and the phase.
subplot(211)
plot(a,20*log10(abs(y)))
xlabel(‘Frequency – Hz’)
ylabel(‘Magnitude – dB’)
tl = [‘Frequency response function K=’ num2str(K) ‘ t=’ num2str(t) ];
eval([‘title(‘’’,tl,’’’)’])
subplot(212)
plot(a,angle(y)*180/pi)
xlabel(‘Frequency – Hz’)
ylabel(‘Phase – degrees’)
print –depsc2 –tiff Figure4

- 18 -
ME365 MATLAB Introduction Notes

Frequency response function K=10 t=0.01


20

15
Magnitude − dB

10

−5
0 100 200 300 400 500 600 700 800 900 1000
Frequency − Hz

−20
Phase − degrees

−40

−60

−80

−100
0 100 200 300 400 500 600 700 800 900 1000
Frequency − Hz

Figure 4: Output from dot command example program fig4.m.

Now let’s do a more complicated calculation. We shall plot a damped sinewave added to a DC
offset for values of time from 0 to 0.1 second. The frequency of the wave is 30 Hz. and the decay
parameter is set to 18. The sampling interval is 0.001 seconds. The amplitude of the wave is 2
Volts and the DC offset is 3 Volts.

%fig5.m program to plot a damped sine plus DC


A=2;
f=30;
al=18;
dc=3;
%
%Set up the time vector
t=(0:0.001:0.1);
x=dc+A*exp(-al*t).*sin(2*pi*f*t);
%
% Note that MATLAB is happy to add a constant to the
% whole vector and does not need a dot before the +
% The exp(-al*t) results in a vector, as does the
% sin(2*pi*f*t), the dot before the * says multiply
% the ith element of exp(-al*t) by the ith element of sin(2*pi*f*t).

- 19 -
ME365 MATLAB Introduction Notes

% The result is stored in x(i).


%
% Now plot
subplot(111)
plot(t,x)
xlabel('time - seconds')
ylabel('Signal Level - V.')
title('Example using the dot command in MATLAB')
print –depsc2 –tiff Figure5

The result of running this program is shown in Figure 5.


Example using the dot command in MATLAB
5

4.5

4
Signal Level − V.

3.5

2.5

1.5
0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1
time − seconds

Figure 5: Output from the second dot command example program.

- 20 -
ME365 MATLAB Introduction Notes

B.3 Calculating and Plotting a Step Response.


In the following program (m-file) the user specifies the system characteristics and the step input
characteristics. The program then plots the step response. Here the sample rate is chosen to be
0.02 times the time constant τ, and the step occurs at t=0. The response is plotted from -τ to +5τ
seconds.

% frstord.m program to plot the step response to a first


% order system.
%
format compact
xi = input('Initial value of the input ');
yi=K*xi;
xst = input('Input step size ');
K = input('System sensitivity ');
tau = input('System time constant ');
%
% Calculate time vectors before and after step.
% Plot for tau seconds before to 5 tau seconds after
% Plot every tau/50 seconds.
%
t1=(-tau:tau/50:0);
t2=(0:tau/50:5*tau);
%
% Calculate the response vectors before and after step.
y1=yi* ones(size(t1));
y2=yi + K*xst - K*xst*(exp(-t2/tau));
%
%plot
subplot(211)
plot([t1,t2],[y1,y2])
xlabel('Time - Seconds')
ylabel('Response - volts')
ch1= num2str(tau);
ch2 = num2str(K);
title([ 'Step response 1st order system: tau =' ch1 ', K =' ch2 ])
xx=axis; xx(3) = yi-0.5*yi; xx(4)= yi + K*xst +0.5*yi; axis(xx);
grid on
print –depsc2 -tiff Figure6

Note the use of the num2str function. This converts a numerical value associated with a variable
into a character string so that it can be included in the figure annotation, in this case in the title.
This is useful to keep track of the variable values used to generate the plot. Also in this file, I have
reset the axes using the axis command. xx(1) is the minimum value on the x-axis, xx(2) is the
maximum value on the x-axis, xx(3) in the minimum value on the y-axis and xx(4) is the maximum
value on the y-axis. The grid command puts the background lines on the graph that make it easier
to read off the values.

- 21 -
ME365 MATLAB Introduction Notes

Step response 1st order system: tau =0.33, K =0.1


3.5
3
Response − volts

2.5
2
1.5
1
0.5
−0.5 0 0.5 1 1.5 2
Time − Seconds
Figure 6: Step response of a first order system.

B.4 Calculating an Plotting a Frequency Response Function.


The last example in this section is calculating and plotting frequency response functions. Here the
system is a second order system with a frequency response function given by:

K .ω 2
G( jω ) = 0
,
ω 02 − ω 2 + j 2ςωω 0
where ω 0 is the undamped natural frequency, K is the sensitivity and ζ is the damping ratio.
Typically we plot the magnitude of this function in dB ( 20 log10 G( jω ) ) and the phase either in
radians or in degrees. The MATLAB function angle will calculate the phase in radians and you
have to convert it to degrees ( × 180 / π ). Both plots are plotted versus frequency (ω ) on a logged
frequency axis. For plotting we therefore use semilogx, rather than plot. The make your points
equispaced on this log scale, we use the function logspace where you specify the start and end of
the frequency axis in exponents of 10. So to generate frequencies from 0.01 to 1000 rad/s and have
2000 equispaced points you type:

>>om = logspace(-2,3,2000);

Remember that MATLAB will assume that j = − 1 unless you set it to something else in your
program (m-file). This function is interesting for two decades below ω 0 to around two decades
above ω 0 . ceil and floor are MATLAB functions that give the nearest integer above and below,
respectively, a given number.

- 22 -
ME365 MATLAB Introduction Notes

% sndord.m This is an example of plotting the frequency response of


% an accelerometer, which behaves like a 2nd order system.
%
% Ask program use to specify second order system characteristics.
%
K = input('System sensitivity = ');
ze = input('Damping ratio = ');
wo = input('Undamped natural frequency = ');
%
% Make character strings of values for labelling.
Kt=num2str(K);zet=num2str(ze);wot=num2str(wo);
%
% Work out what frequencies to use
w_ex_low=floor(log10(wo));
w_ex_up=ceil(log10(wo));
w=logspace(w_ex_low-2,w_ex_up+2,3000);

%
% Now calculate the Frequency Response Function
G=K*wo*wo./(wo*wo-w.*w+j*2*ze*w*wo);
GA=20*log10(abs(G));
GP=angle(G)*180/pi;
%
subplot(211)
semilogx(w,GA)
xlabel('Frequency - rad/s')
ylabel('Magnitude - dB ref 1V/(m/s^2)')
title(['2nd Order Freq. Resp.: K=' Kt ',\zeta=' zet ',\omega_0=' wot])
grid on

subplot(212)
semilogx(w,GP)
xlabel('Frequency - rad/s')
ylabel('Phase - degrees')
grid on
print -djpeg Figure7

The result of running this m-file and giving the values K=10 V/(m/s2), ζ=0.1 and ω0=100 rad/s is
shown in Figure 7a. You may note the 180° phase drop as the plot moves from low frequencies
(well below the undamped natural frequency) to high frequencies (well above the undamped
natural frequency). Below one-tenth of the resonance frequency (peak in the magnitude plot) the
magnitude plot is very flat. Note that the resonance frequency is not quite at the undamped natural
frequency which can be found by identifying where the phase passes through −90°. At high
frequencies the magnitude plot drops by 40 dB every time the frequency increases by a factor of 10,
i.e., in this case the magnitude drops from –20 to –60dB when the frequency goes from 1,000 to
10,000 rad/s. You can some of these characteristics in a much more heavily damped second order
system by setting: K=0.25 V/(m/s2), ζ=2 and ω0=1000 rad/s; the result is shown in Figure 7b. Note
here the damping is so high that no peak appears in the frequency response magnitude.

- 23 -
ME365 MATLAB Introduction Notes

2nd Order Freq Resp: K=10, ζ=0.1,ω =100


0

Magnitude − dB ref 1V/(m/s2)


40

20

−20

−40

−60 0 1 2 3 4
10 10 10 10 10
Frequency − rad/s
0
Phase − degrees

−50

−100

−150

−200 0 1 2 3 4
10 10 10 10 10
Frequency − rad/s

Figure 7a: Frequency response function of an accelerometer that behaves as a


lightly damped second order system.

2nd Order Freq Resp: K=0.25, ζ=2,ω0=1000


Magnitude − dB ref 1V/(m/s )
2

−20

−40

−60

−80

−100 1 2 3 4 5
10 10 10 10 10
Frequency − rad/s
0
Phase − degrees

−50

−100

−150

−200 1 2 3 4 5
10 10 10 10 10
Frequency − rad/s

Figure 7b: Frequency response function of an accelerometer that behaves as a


heavily damped second order system.

- 24 -
ME365 MATLAB Introduction Notes

C. A Little More Sophistication in MATLAB Programming


C.1 Loops in a Fourier Series Example
Below is an example of how to use loops in MATLAB. Again we have put the instruction set in an
m-file. The algebraic expressions for the coefficients of a Fourier series containing sines plus a DC
offset have been calculated by hand earlier. The first 9 non-zero terms of the Fourier series are
being passed through a second order system and summed to give the steady state response of the
system to this periodic excitation.

% four_sys.m
% a file to pass the first 9 non-zero terms of
% a Fourier Series through 2nd Order System.
%
clear
clf
%First specify system characteristics
Ksens=10; zeta=0.01; wnat=10;
%
%
% Now sepecify the Fourier Series Terms
% This is a square wave, so even terms are
% zero, so I am only specifying odd values
% for k.
Tp=1; fund = 1/Tp;
dc=5;

kk=(1:9); %Counter for the terms to sum


k=(kk-1)*2+1; %Index in Fourier Series sum

fk=fund*k;
wk=2*pi*fund*k; % Frequencies in rad/s
M=10./(pi*k); % Amplitudes
phi=0*ones(size(M)); % Phases

% Generate Input Term by Term and sum up


fs=10*max(fk); del=1./fs; % Set sampling frequency and interval.
t=(0:del:3*Tp); % Time vector
x=dc*ones(size(t));
for kk=1:9;
x=x+M(kk).*sin(wk(kk)*t+phi(kk));
end

% Generate F.S. Coefficients for SS-Output


G=Ksens*wnat*wnat./(wnat^2-wk.^2+j*2*zeta*wnat.*wk);
Gmag=abs(G);
Gpha=angle(G);

M_out=M.*Gmag;
phi_out=phi+Gpha;

- 25 -
ME365 MATLAB Introduction Notes

dc_out=dc*Ksens;

% Generate SS-Output Term by Term and add them up.


y=dc_out*ones(size(t));
for kk=1:9;
y=y+M_out(kk).*sin(wk(kk)*t+phi_out(kk));
end

subplot(221)
plot(t,x)
xlabel('Time - seconds')
ylabel('Input')
title('Fourier Series Example')

subplot(222)
plot(t,y)
xlabel('Time - seconds')
ylabel('SS-Output')
title('System has attenuated higher frequencies')
print -depsc -tiff Figure8

This produces the following plot.

Fourier Series Example System has attenuated higher frequencies


8 120

7 100

80
6
SS−Output

60
Input

5
40
4
20
3 0

2 −20
0 1 2 3 0 1 2 3
Time − seconds Time − seconds

Figure 8: Fourier series example, passing the first 9 non-zero terms of a square
wave through a second order system: K=10, ωn=10, ζ=0.01. Input and steady-state
response are shown.

- 26 -
ME365 MATLAB Introduction Notes

C.2 If Statements
The if statement has the form:

if expression
statements
elseif expression
statements
else
statements
end

Following is an example of its use. In this program (m-file) terms in a uniformly distributed
random number sequence will be set to 1, 0 or −1 depending on whether the value is greater than
0.33, between −0.34 and 0.33, or less than −0.34, respectively.

% ex_if.m program to illustrate if statement usage.


%
M=input('How many values ');
%
%Initiate Random Number Sequence
rand('seed',sum(1000*clock));
%
%Generate the random number sequence
a=-1+2*rand(1,M);
%
[max(a),min(a),mean(a)]
%
for j=1:M
if a(j) < -0.34
x=-1;
elseif a(j) <=0.33 & a(j) >= -0.34
x=0;
else
x=1;
end
a(j)=x;
end

C.3 While Statements


The form of the while statement is:

while expression
statements
end

- 27 -
ME365 MATLAB Introduction Notes

Here is a very simple example of using a while loop. You can solve this equation by using the
quadratic formula. This iteration converges to one of the solutions, usually x = 1.

%whi.m while loop illustration


% iterative solution of x^2 + x – 2 = 0.
%
xn = input(‘Initial Guess = ‘)
er = 100;
%
while er > 0.0001
if xn == 0
xo=0.001;
else
xo = xn;
end
xn = 2/(1+xo);
er = abs(xn-xo);
end
sprintf('Error was: %0.5g; Solution is: %0.5g ',er,xo)

The sprintf program allows you to print out formatted text and numbers and is useful for creating
output to copy into a report.

C.4 Subroutines/Functions
When you wish to do calculations of the same form many times, it is often more convenient to
write a function which is just an m-file containing the calculation instructions. The m-file and the
function share a common name. So if you have a function called greenf, it will be stored in a file
called greenf.m. The only problem that can arise (as with all m-files) is perhaps MATLAB has a
function of the same name, and then MATLAB gets confused.

Suppose we wished to do the integration of the Gaussian many times (as we do in a χ2 test), and
each time we are integrating across different limits. Below is a subroutine that uses the inbuilt
MATLAB function erf to integrate a Gaussian function from x1 to x2, given the mean and standard
deviation that defines the Gaussian function. The subroutine would be stored in file gaus.m and
called gaus when called from the main program.

%gaus.m function to integrate a Gaussian


% inputs: mu - mean
% st - standard deviation
% x1 - lower limit
% x2 - upper limit
% output res - the result of the integration, a number
% between 0 and 1.
%
function [res] = gaus(mu,st,x1,x2)
%
% change of variables
z1=(x1-mu)/(sqrt(2)*st);

- 28 -
ME365 MATLAB Introduction Notes

z2=(x2-mu)/(sqrt(2)*st);
%
%Calculation using the erf function
res = (erf(z2) - erf(z1))/2

Calling this function from another m-file is illustrated in the following example. Bin limits are
specified for 9 bins, binl is a vector of the lower edges of the bins and binu is a vector of the upper
edges of the bins. The mean and standard deviation of the data are also input by the m-file user.
The result of the integrations are stored in pro.

%chi.m program to integrate a Gaussian over a series of


% bin limits.
%
%Specify bin limits
%
format compact
binl=[ -2 -1.5 -1. -0.5 0. 0.5 1.0 1.5 2.0 ];
binu=[ -1.5 -1. -0.5 0. 0.5 1.0 1.5 2.0 2.5];
%
% Ask user for mean and standard deviation of data
me = input('Mean value of data ');
stt= input('Standard deviation ');
%
% Use gaus.m to do the integrations.
pro=gaus(me,stt,binl,binu)
%
% Add up all the integrations.
total_area=sum(pro)
%

Note that we did not have to use a loop and the subroutine did element by element calculations
automatically, hence requiring only one call to the function. In general, you would have to be
careful with the "dreaded" dot command to make sure that your function will do element by
element calculations when presented with vectors rather than scalars. Making the variable stt a
vector would cause an error as the function exists in its current format. Functions can have more
than one output variable. Type:

>>
>>help function
>>

to see an example for calculating the mean and standard deviation of a data set.

C.5 Changing graph font sizes and line thickness, etc.


When the graphics window comes up, you can edit the graph with “point and click”, but it gets
tedious to do this for every graph you put in a report. To do this in the program (m-file) is
complicated and certainly not too intuitive. Following is a simple function that will change the

- 29 -
ME365 MATLAB Introduction Notes

fontsize and line thickness of the current plot. This is also useful when you are making plots for
presentations because the graphs often need some editing before they look good in a presentation,
and more importantly you can read the axis values and labels.

%vividoc.m
function [] = vividoc(fonts,lines);
%fonts = fontsize. Something between 12 and 18.
%lines = linethickness. Something around 1 to 2.
set(gca,'Fontsize',fonts);
hhh=get(gca,'Children');
for i=1:length(hhh)
set(hhh(i),'LineWidth',lines);
end
hhx=get(gca,'XLabel');
set(hhx,'Fontsize',fonts);
hhy=get(gca,'YLabel');
set(hhy,'Fontsize',fonts);
hht=get(gca,'Title');
set(hht,'Fontsize',fonts);

I call this after every subplot is “complete”, that is, after I have done all the labels and titles. So the
structure would be:

subplot(211)
plot…..
xlabel(….
ylabel(…
title(‘….
vividoc(14,1.2)

subplot(212)
plot…..
xlabel(….
ylabel(…
title(‘….
vividoc(14,1.2)

When you have markers, rather than just lines, on the plots, you have to do a bit more work than
this vividoc function does, but you can change the size of markers and fill them by using similar
commands. The file below is an example of how to fill in and manipulate markers and labels for
markers.

% spotsfont.m controlling font and spot size


%
% Simulate some data for plotting
x1=(1:10);y1=2*x1.^2;
x2=(1:10);y2=4-0.2*x2.^3;
x3=(1:10);y3=3*x3.^2;
%
%

- 30 -
ME365 MATLAB Introduction Notes

figure(1)
plot(x1,y1,'bo',x2,y2,'g^',x3,y3,'r*')
%
% Instead of using gca and gcf, as in vividoc.m above you
% can get the graphics handles in the following manner:
l(1)=xlabel('x-values');
l(2)=ylabel('y-values');
l(3)=title('Testing spots');
set(l(1:3),'Fontsize',[16]);
%
% The axis values on the graph are Children of the plot
% So we first get the handle number for the Children
% Then change the fontsize.
af = get(gcf,'Children');
set(af,'FontSize',[16]);
%
% Now fill in the markers on the plots: Blue, Green, Red
% Note the aa(3) is actually related to the first data plotted!
% This is confusing, hence I'm getting the color,
% and filling in the Face with the color.
aa = get(gca,'Children');

% First data plotted


pp=get(aa(3),'Color')
set(aa(3),'MarkerFaceColor',pp)
set(aa(3),'MarkerSize',[8])

%Second data set plotted


pp=get(aa(2),'Color')
set(aa(2),'MarkerFaceColor',pp)
set(aa(2),'MarkerSize',[8])

%Third data set plotted


pp=get(aa(1),'Color')
set(aa(1),'MarkerFaceColor',pp)
set(aa(1),'MarkerSize',[8])

% Make labels for the second plot.


% Suppose the values come from an analysis on files 1 to 10,
% so make the labels the file number
x1l=[1:9,10]';
%Change the numbers to character variables
%strcat deals with labels of different lengths
x1lab=strcat(int2str(x1l));
% Alternatively we could have written:
% x1lab=strcat('1';'2';'3';'4';'5';'6';'7';'8';'9';'10');
g=text(x2,y2,x1lab);
%
% Not specifying array element in next three lines allows
% us to make the same setting for all labels 1 through 10.
set(g,'Fontsize',[14]);

- 31 -
ME365 MATLAB Introduction Notes

set(g,'HorizontalAlignment','right');
set(g,'VerticalAlignment','top');
%Adjust the 10th point alignment
set(g(10),'HorizontalAlignment','left');
set(g(10),'VerticalAlignment','bottom');

% Set up Legend then change the properties of the Legend


r2ah(1)=0.99; r2ah(2)=0.94; r2ah(3)=0.90;
names(1,1:12)='Graph One ';
names(2,1:12)='Graph Two ';
names(3,1:12)='Graph Three ';
eval(['h=legend(''',names(1,1:12),'
R^2=',num2str(r2ah(1)),''',''',names(2,1:12),'
R^2=',num2str(r2ah(2)),''',''',names(3,1:12),'
R^2=',num2str(r2ah(3)),''');'])
%
% Position is bottom left: x y followed by box size: x y
% all normalized to the range 0 to 1.
% 0,0 bottom left of window 1,1 top right
%
set(h,'Position',[0.15 0.6 0.5 0.25])
set(h,'Fontsize',[12])

After running this m-file we get the plot in Figure9.

Testing spots
300

250 2
Graph One R =0.99
Graph Two R2=0.94
200 Graph Three R2=0.9

150

100
y−values

50

0 1 2 3 4
5
−50 6
7
−100 8

−150 9
10
−200
0 2 4 6 8 10
x−values
Figure 9: Output of spotsfonts.m program illustrating how to fill in and change size
of markers.

- 32 -

Potrebbero piacerti anche