Data and Function Plotting with MATLAB (Linux-10)

Similar documents
Fitting data with Matlab

Lab1: Use of Word and Excel

APPM 2460 PLOTTING IN MATLAB

Grace days can not be used for this assignment

Name: Dr. Fritz Wilhelm Lab 1, Presentation of lab reports Page # 1 of 7 5/17/2012 Physics 120 Section: ####

To Plot a Graph in Origin. Example: Number of Counts from a Geiger- Müller Tube as a Function of Supply Voltage

Desktop Command window

MATLAB INTRODUCTION. Matlab can be used interactively as a super hand calculator, or, more powerfully, run using scripts (i.e., programs).

Administrivia. Next Monday is Thanksgiving holiday. Tuesday and Wednesday the lab will be open for make-up labs. Lecture as usual on Thursday.

An introduction to plotting data

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

Microsoft Word for Report-Writing (2016 Version)

MATLAB Project: Getting Started with MATLAB

Getting Started. Chapter 1. How to Get Matlab. 1.1 Before We Begin Matlab to Accompany Lay s Linear Algebra Text

A Guide to Using Some Basic MATLAB Functions

Introduction to Matlab to Accompany Linear Algebra. Douglas Hundley Department of Mathematics and Statistics Whitman College

Excel Spreadsheets and Graphs

ENVI Tutorial: Introduction to ENVI

1 Introduction to Matlab

MATLAB - Lecture # 4

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

MATLAB Introduction to MATLAB Programming

MATLAB Introductory Course Computer Exercise Session

Matlab Tutorial 1: Working with variables, arrays, and plotting

0 Graphical Analysis Use of Excel

A quick Matlab tutorial

Introduction to Spreadsheets

MATLAB BASICS. < Any system: Enter quit at Matlab prompt < PC/Windows: Close command window < To interrupt execution: Enter Ctrl-c.

STAT 391 Handout 1 Making Plots with Matlab Mar 26, 2006

Pre-Lab Excel Problem

Exercise: Graphing and Least Squares Fitting in Quattro Pro

What is MATLAB and howtostart it up?

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

AMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA

Experimental Physics I & II "Junior Lab"

AMS 27L LAB #2 Winter 2009

= 3 + (5*4) + (1/2)*(4/2)^2.

You will learn: The structure of the Stata interface How to open files in Stata How to modify variable and value labels How to manipulate variables

Assignment 2 in Simulation of Telesystems Laboratory exercise: Introduction to Simulink and Communications Blockset

Computer Data Analysis and Use of Excel

Introduction to Motion

Part I. Introduction to Linux

Chapter 3: Rate Laws Excel Tutorial on Fitting logarithmic data

EGR 111 Plotting Data

Exercise sheet 1 To be corrected in tutorials in the week from 23/10/2017 to 27/10/2017

Excel Primer CH141 Fall, 2017

Objectives. 1 Basic Calculations. 2 Matrix Algebra. Physical Sciences 12a Lab 0 Spring 2016

Experimental Design and Graphical Analysis of Data

Plotting Graphs. Error Bars

Section 4.4: Parabolas

Week 1: Introduction to R, part 1

An SM tutorial for programming and plotting

Using the Zoo Workstations

Introduction to the MATLAB SIMULINK Program

Capstone Appendix. A guide to your lab computer software

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

Getting Started With Linux and Fortran Part 2

Activity Graphical Analysis with Excel and Logger Pro

The value of f(t) at t = 0 is the first element of the vector and is obtained by

ENVI Classic Tutorial: Introduction to ENVI Classic 2

MATLAB Project: Getting Started with MATLAB

GRAPHICS AND VISUALISATION WITH MATLAB

Introduction to Stata. Getting Started. This is the simple command syntax in Stata and more conditions can be added as shown in the examples.

Physics 101, Lab 1: LINEAR KINEMATICS PREDICTION SHEET

Logger Pro Resource Sheet

Objectives. 1 Running, and Interface Layout. 2 Toolboxes, Documentation and Tutorials. 3 Basic Calculations. PS 12a Laboratory 1 Spring 2014

CSE/NEUBEH 528 Homework 0: Introduction to Matlab

INSTRUCTIONS FOR USING MICROSOFT EXCEL PERFORMING DESCRIPTIVE AND INFERENTIAL STATISTICS AND GRAPHING

Matlab Tutorial: Basics

Introduction to Unix and Matlab

Getting Started with MATLAB

Lab 1- Introduction to Motion

Lab 5: Program Control and Functions

Introduction to MatLab. Introduction to MatLab K. Craig 1

Getting To Know Matlab

Introduction to Computer Graphics and Computer Vision Assignment 3: Due 7/27/2015

Error Analysis, Statistics and Graphing

A Simple First-Model Using the Berkeley-Madonna Program

ENVI Tutorial: Interactive Display Functions

Data Management Project Using Software to Carry Out Data Analysis Tasks

Introduction to Matlab

For the SIA Features of GigaView. Introduction. Initial Dialog Bar

Computational Approach to Materials Science and Engineering

Introduction to Minitab 1

SPSS 11.5 for Windows Assignment 2

Getting Started with MATLAB

Getting Started With UNIX Lab Exercises

A brief Tutorial of the CLASS Data Reduction Program

Dr. Barbara Morgan Quantitative Methods

MATLAB Tutorial. Primary Author: Shoumik Chatterjee Secondary Author: Dr. Chuan Li

Laboratory 1 Octave Tutorial

Experiment 1 CH Fall 2004 INTRODUCTION TO SPREADSHEETS

Introduction to MATLAB

Department of Chemical Engineering ChE-101: Approaches to Chemical Engineering Problem Solving MATLAB Tutorial Vb

Introduction to IgorPro

EE168 Lab/Homework #1 Introduction to Digital Image Processing Handout #3

Lab 1 Introduction to R

Microsoft Excel Using Excel in the Science Classroom

ME422 Mechanical Control Systems Matlab/Simulink Hints and Tips

Eric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example:

Transcription:

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