Data Plotting with MATLAB and PLOT1

[Pages:5]Data and Function Plotting with MATLAB

(Linux-10)

This tutorial describes the use of MATLAB for general plotting of experimental data and equations and for special plots like histograms. (Astronomers - see Appendix for plotting of fits file images.) Paste printouts of your plots into your lab notebook.

A. Prerequisites. You must have completed the Login/GEdit tutorial and the MATLAB introduction tutorial. You should have created the files first.dat and firstplt.m already.

B. Reference. Getting Started with MATLAB 7, Pratap.

C. Introduction to MATLAB plotting. MATLAB can operate on data files to produce high quality plots with automatic scaling, labeled axes, titles, errorbars, and so forth. The plots can be proofed on the screen and then printed on the laser printer. You can work interactively with MATLAB plotting, and you can also store sets of commands in a "script", or ".m" file in order to easily repeat the same type of plot with different data sets. In the first computer tutorial you created a data file first.dat containing a sample set of x- and y- data values (plus y-uncertainties) to be plotted by MATLAB. You also created a script instruction file firstplt.m which tells MATLAB how to draw a particular plot with this data. We just need to start MATLAB and execute the script.

To begin plotting, log in and open a terminal window as before, and then type

matlab

at the terminal command prompt (or click on the MATLAB icon if on a Windows computer). MATLAB should display a title screen and then indicate with its prompt >> that it is ready to receive commands. Now proceed to execute the script firstplt.m by just typing

firstplt

A graphics window should have appeared on the screen with the plot in it. If the plot is satisfactory, you can type print at the MATLAB command prompt to get a hard copy on the laser printer, or else select the print command from the print menu above the graph window. (If you get an error message saying that firstplt is an unknown command, or that first.dat cannot be found, it is because the files you created with Kedit or GEdit are not in MATLAB's "Current Directory". The Current Directory is shown in a menu-window just above the command window; you can change the current directory with a "cd directory" at the MATLAB command line, or by using the browse button with three dots on it. You could also move your files into the standard MATLAB "working" directory. See Pratap Chap. 2 for more details.)

Things to notice: The datapoints are plotted as points with y-errorbars and are not connected with line segments. Each axis has a label indicating what is plotted, with the units in parentheses. (This is theway data plots should always be done!) Look at the menu bar at the top of the figure window. Click on the "data cursor" icon and use the cursor to read out some of the data values from the plot. Under the "tools" menu, look at "Data Statistics" and also at "Basic Fitting." Use Basic Fitting to fit a quadratic equation to the plotted data. You can also explore the "Insert" menu and try inserting an arrow on the plot. Remember to print off a copy of the plot from the "File" menu.

The Pratap book (or MATLAB Primer) shows some other MATLAB graphics commands that may be useful later on. Note that you can get the details of any command by typing help followed by the command name. You can also get general help by typing helpwin and using the menu structure. For your homework later on, you will want to use some of the following graphics commands:

hist (y)

hist(y,nb) hold on

bar gtext('text')

Creates a histogram of the values in the array y using 10 bins equally spaced between the minimum and maximum values of y. If you want a number nb of bins, use the command:

Causes new plots to be superimposed on an existing plot Remember to use "hold off" when you are done superposing To create a bar graph Places text on the plot at a location you choose with the mouse

Also, MATLAB text objects support a subset of TeX characters that enable you to use symbols and superscripts in axis labels or titles. For example, \alpha produces the Greek alpha character, and the string ^{-t} would cause -t to be a superscript. See the text function in the online MATLAB help for a list of available TeX characters.

Note that you can overlay plots by using hold , reading in a new data file, and defining a new plot before erasing an old plot. This can be useful in plotting a theoretical curve over a set of experimental points, etc. (You need to be sure that the x- and y-axis ranges are compatible.)

A script similar to firstplt.m can be written which will be useful for doing errorbar plots of any data file which has three columns representing the x,y, and y-errorbar values for each data point. I recommend that you prepare (using Gedit or, more conveniently, the built-in editor in MATLAB) a file (saved as eplot.m) as follows:

datafile=input(`Input the data file name `,'s'); data=load (datafile) x=data(:,1); y=data(:,2); e=data(:,3); errorbar(x,y,e,e,'*')

After you run the script, you can add appropriate labels using the xlabel, ylabel, and title commands (look at the script firstplt.m to see how to use these commands.

In creating a new data file to be plotted by eplot, make sure that it is an ASCII, or text, file and that it has three numbers per line (x, y, and delta-y, where delta-y is the uncertainty in the y value) separated by spaces. Also, be sure that the data file does not contain any blank lines, either before or after the data. Sometimes the editor program will jump to the next line for you and leave a blank line if you don't enter anything. If no errorbars are needed, you can enter zeros in the errorbar position, or much better, enter a small uncertainty estimate.

As discussed in class, in some cases you will want to "linearize" a plot by plotting some function of the measured data on one of the axes. If you get your measured data into x, y, and e arrays, you can

2

transform the data for linearization by using commands such as y = y.*y (to transform each array element by squaring it), and to transform the y-uncertainty array with commands such as e = e./y . (Notice the use of dot operators!) Be sure to transform the uncertainty array before transforming data arrays (why?).

To complete the tutorial, use MATLAB to plot data from one of the homework problems, such as a histogram of the data for a problem from Homework Set 2.

D. User-Defined Functions and Plotting of Functions

D1. - Function Definition. If you often do certain MATLAB calculations which involve a particular function that is not built in to MATLAB, you may want to write a MATLAB function definition. For example, here's a script file to define the function gssn (t,tmean,tstd), which calculates the Gaussian probability density for an input value of t when the mean is tmean and the standard deviation is tstd. You must use an editor to prepare and save the function definition below as an m-file with the name gssn.m

function gs = gssn(t,tmean,tstd) gs = exp(-(t-tmean).^2/(2*tstd^2))/(tstd*(2*pi)^.5)

If you wanted to compute the value of the integral of the Gaussian PDF from t=lowlimit to t=uplimit, you could use the quad function of MATLAB along with your function definition. It would go something like this (don't actually try this one, of course, since you would need values for the parameters )

y = quad(`gssn',lowlimit,uplimit, 1e-3,[],Mean,StDev)

For example, if you wanted to integrate a Gaussian with mean=0 and standard deviation = 2 from -2 to +2, you would write

quad('gssn',-2,2, 1e-3,[],0,2)

Try it - you should know what answer to expect! Put your prediction and result in the lab notebook.

D2. Function Plotting

To plot a function, you can define an "x" array of independent variable values (i.e., an array of arguments at which the function is to be evaluated) and a "y" array of function values at those x values. Here's an example with a Gaussian function with mean =5 and standard deviation = 1:

x=0:.01:10;

This generates a 1001 point array ranging from 0 to 10 in steps of 0.01

y=gssn(x,5,1);

plot (x,y)

xlabel (`Voltage (V)')

ylabel (`Probability Density (V^{-1})')

Remember that you can superimpose this plot on a plot of experimental data by using the hold command. If doing so, you should be sure that the range of x (independent variable) values is the

3

same for both plots. Here, we used the plot command, which does connect the points with line segments, as is appropriate when plotting a theoretical curve.

You should use this approach on the appropriate problem of Homework Set 2.

Paste the plots from this session in your lab notebook along with a copy of your plotting script.

E. PLOT1 for Linear Least-Squares Fits. The MATLAB script plot1 (the file is plot1.m) will take a file of x,y,delta-y data [i.e., a file with three columns of data: x, y, and delta-y, where delta-y is the uncertainty in the y-value] and perform a linear least-squares fit on it, provide the slope and intercept of the line and the uncertainties in these two parameters, and plot the data (with error bars) and the fitted line. The correlation coefficient and chi-squared values for the plot will be indicated (you will hear more about these parameters soon).

Your data must be in a text, or character-type data file. (When you run the program, it will prompt you for the name of the data file to be plotted.) The file must have x in the first column, y in the second, and delta-y in the third. Use spaces to separate data fields, not tabs. Also, do not leave blank lines in the data file, either before or after the data. Data points will be plotted with y-errorbars, and the points will be weighted according to their uncertainty. Zeros in the delta-y column will probably cause an overflow; use small delta-y values if the actual delta-y values are unknown.

The plot1.m file should be found in the Physics 710 directory [/Users/student/710/plot1.m]. You should copy it to your home directory or your MATLAB working directory so it will be available for you to use like your own .m files. To copy this file into your home directory, type in the following command at the UNIX command prompt:

cp /Users/student/710/plot1.m plot1.m

You can use your first.dat data file as a trial if you like (although those data do not fit a straight line all that well).

You will need to use plot1 for one of the problems on homework set 3 and in many other situations during the course. You should also find it useful in your later work.

If you need to linearize your data in order to make the dependent variable a linear function of the independent variable, you can write some lines of MATLAB code to transform the x-values and/or the y- and delta-y values as needed. One way to do this is to start with the plot1.m script, add the transformation lines (remember that MATLAB can transform a whole array with just one command!) between where the data is read in and where the plotting and fitting begin, and then save the script under a new file name (e.g., voltplot.m). It is best to NOT overwrite the original plot1.m file, so you always have it available as a starting point.

Enjoy!

4

Appendix ? Plotting fits Images (FITS file and some material below courtesy Dr. Alberto Bolatto, Astronomy Dept., U. of Maryland)

Astronomical image data is frequently saved in the FITS (Flexible Image Transport System) format. FITS files, which MATLAB can read and display, have two parts: a header section (which has information about when and how the data were obtained, coordinate systems, units, etc.) and a data section (the raw image data, stored as binary numbers).

The MATLAB command fitsread will read the primary image data of a FITS file. For example, the command

idata = fitsread(filename);

would put the image data from fits file filename into the matrix idata. The filename argument is a string enclosed in single quotes, like `M83.fits'

If you would like to try this, copy the file n4254_pr.fits from the 710 directory in the same way that you copied the plot1.m script (from the UNIX command line, you would enter cp /Users/student/710/n4254_pr.fits n4254_pr.fits ).

Then try the following commands

idata = fitsread(`n4254_pr.fits'); imagesc(idata) axis image set(gca,'ydir','nor')

to read in a FITS image of NGC 4254 (M99) into MATLAB, display it as an image, format the axes so that it displays square pixels, and orient it properly so that right is West and up is North.

A useful image manipulation is to change the range of intensities in the display using the MATLAB caxis command. Try

caxis([1900 3000])

which should let you see the details of the outer spiral arms at the cost of saturating the nucleus. Too see the nucleus and spiral arms at the same time, you could display the logarithm of the intensity values as follows:

imagesc(log(idata')); caxis ([7.5 8.9]}

5

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download