A Quick Introduction to Matlab for Laboratory Analysis QLab Team, Department of Physics, CalPoly, San Luis Obispo, CA (version: Sept, 2013) Matlab Environment: When you start Matlab it provides you with a Graphical User Interface (GUI) designed to help you do technical calculations. The Command Window is the place you will type in the commands you want executed immediately. You can also save commands in a file which is run like a conventional computer program. A variety of other windows are also displayed and eventually you’ll find yourself using their information, or customizing the windows that you want displayed. When you save your work, it will put the files in the folder (directory) indicated on the top bar. Make a folder on the desktop to hold all the work you and your lab partner do this quarter. Switch to this folder in the top bar so that your files will travel with you and be accessible from other machines. (We are discouraging the use of flash drives. You may email files to yourself as needed.) Folder for your files. Type commands here. As with any programming language, the syntax looks like Greek when you first see it and must be learned over time. In the text that follows, commands in red can be copied and pasted to the command window just as you might copy and paste them into Excel or Word. As you read, you should execute each line below to understand what they do. Get a Clean Start: If you’ve been working for awhile and need to clean out all the memory and erase the plots to start over type the following in the Command Window. clear all; close all; Page 1 Arrays: Matlab is based on processing arrays. Calculations will be very inefficient if you don’t use the array syntax. Because it’s central to the design of the language, it’s important to get proficient at manipulating them. A basic one-dimensional vector is created with the syntax: x = startValue:stepSize:endValue; x = 1:1:10; Try pasting this into the command line with and without the semicolon at the end. x = 1:1:10 In Matlab any statement without a final “;” will print its value to the screen. There is no need to add print statements. Just add the semicolons when you get tired of seeing all the output. It’s very handy for debugging to remove a semicolon wherever you’re in doubt about what’s going on. There is also another alternative that some people prefer to make linearly spaced points: linspace(startValue, endValue, numberOfPoints). x = linspace(1,10,10) It’s also possible to make arrays from data points that are not perfectly spaced by entering the data manually: xdata = [1.05 3.55 6.14 9.99] When you collect data by hand you’ll need to enter it into Matlab this way. A couple of matrix utilities may also come in handy. The size(array) function returns the dimensions, [nrows, ncols], of the array. [nrows,ncols] = size(x) Comments: Comments can be added anywhere in Matlab code by putting a % in front of the text. x = 1:1:10 % this is an array with range 1-10. In this document we’ve turned comments green but that’s not a Matlab requirement. Both the red and green can be copied and pasted and Matlab will ignore anything after the % sign. Help: There are lots of ways to find out about Matlab commands. When I was preparing for QLab, I googled “Matlab plotting with error bars” to get advice. You will find lots of advice online. There is also a Help button on the toolbar and sometimes it’s useful to type help on the command line. help plot This displays everything about the plot command with examples that you can cut and paste into your command window. At the bottom of the help information there are links to other functions that are related to plot, so you can often find just what you’re looking for. There is also a search feature from the Matlab Help menu. Functions: There are lots of built-in functions: help elfun help specfun As you need more functions, use help to find the others. Page 2 After defining x = 1:1:10, you can use the various functions on the x-array. y1 = sin(x); y2 = log(x); % this is the natural log y3 = log10(x); % this is log with base 10 y4 = besselj(1,x); Lots of times I make my own functions. Here’s how to write y = x5. y = x.^5 The ^ symbol is used to denote an exponent. The period tells Matlab to do this math on every element of x. Without the period Matlab tries to treat the x array as a matrix and do matrix algebra. You need dots for multiplication and division too. z = x.*y; % multiply arrays element by element z = x./y; % divide arrays Just to prove that you need the periods, try some math without the dots. y = x^2 % this gives errors! y = x.^2 % voila! This works. !!! If something is not working properly try to fix the periods !!! Plotting: To plot the functions above as y (vertical) vs x (horizontal), copy and paste the following to the Command Window. plot(x,y) You should be seeing a basic plot. plot(x,y2,x,y3) % plot two functions at once Are there two functions on the plot? The default is to plot the first function in blue and the second in green. plot(x,90000./x.^2) % plot a function w/o precalculating y This plot wasn’t precalculated. Now we just need to label the axes. xlabel('V (volts)') ylabel('dist (meters)') You’ll want to change the axis limits occasionally with axis axis([1 5 -1e5 1e5]) It is possible to specify color, line styles, and markers (such as plus signs or circles) when you plot your data using the plot command plot(x,y,'color_style_marker'). The color_style_marker is a string containing from one to four characters (enclosed in single quotation marks) constructed from a color, a line style, and a marker type. The strings are composed of combinations of the following elements. Please use “help plot” or read the Matlab documentation for a complete description. http://www.mathworks.com/help/techdoc/learn_matlab/f3-27853.html A few examples will show the differences. plot(x,y,'r-') % plot a function as a smooth curve. A ‘r-‘ will make a smooth red curve for theory plot(x,y,'.g') % plot data as points. A ‘.g’ will plot green dots for data. Page 3 plot(x,y,'+b') % plot data as plus signs. A ‘+b’ will plot blue plus signs for data. You don’t have to worry which comes first, the symbol or the color: ‘+b’ is just like ‘b+’. If you need a logarithmic plot, have a look at the documentation for semilogx(x,y), semilogy(x,y), or loglog(x,y). Plotting with Error Bars: To analyze data, you’ll have to consider error bars, y ± d y . If the error in y is 10% of the value of y, then the error bars are: dy = 0.1*y; To plot data points with error bars, there is an errorbar plot. errorbar(x,y,dy,'.b') % plot data points with error bars Finally, to put plots in different figure windows, use the figure(#) command before plotting. figure(5) plot(x,y) figure(6) plot(x,y2,x,y3) You should see the error bars in Figure 1, and the functions in Figures 5 and 6. Move the plots so that you can see them all simultaneously. Numbers: Here’s how you enter numbers in scientific notation. K = 8.99e9 Pi () should never be entered yourself as 3.14159… you’ll make a deadly typo someday. Please use the built in pi. It will never have a typo and is far more accurate. pi This prints only the first 5 digits to the screen, but there are many more digits in the computer’s memory that will be used in calculations. You can see more digits with: format long. Continuation Lines: If a line is too long you’ll want to continue it on the next line. Matlab understands that “...” means that you’re not done with the line. Here’s an example. y = cos(5) + sin(5) + tan(0.1) ... + 1000 - acos(0.5) Example #1: Plotting a Function as a smooth curve Make an array of values x = [0, 0.02, 0.04, …, 3.0], i.e. 0<x<3.0 with a step size of 0.02. Then plot sin(x) vs x. Label the axes. clear all; close all; x = 0:0.02:3.0; % array of x=values plot(x,sin(pi*x)) % plot sin(pi*x) vs x xlabel('x') % and then label the axes ylabel('sin(pi*x)') Page 4 Example #2: Plotting Data Points with Error Bars Sometimes you will have an explicit set of data points that need to be plotted. Let's see how we can do this. clear all; close all; % Enter the data and error bars by hand. x = [1 2 3.5 5 6.7] t = [2 4 9 15 19.5] dt = [0.4 0.4 0.2 0.4 0.6] % Plot the data with error bars errorbar(x,t,dt,'r.') % Don’t forget the labels xlabel('x (m)') ylabel('t (s)') Data Analysis Scripts Its important (!!!) that you learn to save your analysis in a script. Theses are files that contain a sequence of commands that can be run by typing the file name into the command window. Since script files have the extension .m, they are often called M-files. I will guarantee that something will need to be adjusted later and that changing a line or two is much easier than doing the whole thing from scratch again on the command line. What working physicists do is test a line on the command line and then move it to a script that can be run, modified, and rerun. To open a file, click on the File button in the upper left hand corner of the Matlab window. Choose New and then Script (or M-file in older versions). This brings up an empty window. Copy and paste the following red and green Matlab code into the blank window. clear all; close all; %% % Enter the measured data points by hand x = [-10 -9 -8 -7 -6 -5 -4 -3 0]; y = [2.65 2.10 1.90 1.40 1.00 0.80 0.60 0.30 0.00]; ey = [0.1 0.1 0.1 0.1 0.05 0.05 0.05 0.05 0.2]; % Plot the data with error bars figure(1) errorbar(x,y,ey,'b.') % Don’t forget the labels xlabel('x (mm)') ylabel('y (mm)') axis equal %% hold on % Do something else now that the first part works. hold off %% Page 5 % Do something in a second figure window. %figure(5) %plot(x,x.^2) Save the file with a name like practice_analysis.m.Note that this file will be saved into the current directory (and which is shown at the top bar of the command window) Run the script by pressing green arrow in the editor window. You can also run it by pressing the F5 key or typing its name without the .m on the command line. You can add more plots and analysis to this file to turn in. The only thing to be careful about is the filename. Matlab filenames cannot have whitespace or strange characters in the name. Adding curves and lines to your plots. Run your script again. After plotting your data, open the “Tools” menu item in the Figure window and select “Basic Fitting”. You can add various curves and display the fitted values. Can you make a plot like the following? You will also sometimes need to add your own functions to the script. Find the “hold on” in your script. Replace the “do something else” comment with the following: % Add a cyan line y = m*x + b m = -0.1; b = 0.5; plot(x,m*x+b,'c-'); Page 6 As nice as this is, sometimes you just want a line defined by the endpoints: % Add a line defined by its end points. line([-10 0],[2.5 0],'Color','g') These lines of code should be added to your script. Notice that anything you add to the plot with the Basic Fitting GUI is lost each time you run the program. To save the results you’ll want to put the equations into the script. Even if you find them with the GUI, type the equations into the script. Fitting Theory Parameters Based on Measured Data You will write several fitting programs by the end of this quarter. These will be your primary fitting tools. However, there are times when you need something more sophisticated than we want to write ourselves. We will use Malab’s fit function for some applications. You will still use the practice_analysis.m script. Just be careful with the “hold off” command in the end! As an example, the data in the practice_analysis.m script is supposed to lie on a circle, y = - a 2 - (x - b)2 + c . We will define an anonymous function for the circle equation. % function to fit fun = @(a,b,c,x) -sqrt(a^2-(x-b).^2)+c; % Find a starting point for the parameters a, b, and c. guess = fun(15,0,15,x); % fun(a,b,c,x) plot(x,guess,'r:') The anonymous function has parameters a, b, c and an x-value. Note the use of the “@” symbol in defining your function. Fitters don’t work without a reasonable starting point for the parameters. Before you try to fit anything, find parameters that plot up reasonably close to the data. This will take a while and surely require careful thought. Once you have a curve that is somewhat related to the data, the fitter can hone in on the best answer. The plot of the fitted model convinces me that it does a nice job. % fit the data (Matlab version R2011a and later) fittedmodel = fit(x',y',fun,'StartPoint',[15 0 15]) % plot the result plot(fittedmodel,'r-'); If you are using your own laptop and have an older version of Matlab (check by typing ``version”), you’ll need to pass a fittype to the fitter instead of an anonymous function: % fit the data (Matlab version R2008b) ftfun = fittype('-sqrt(a^2-(x-b).^2)+c'); fittedmodel = fit(x',y',ftfun,'StartPoint',[15 0 15]) % plot the result plot(fittedmodel,'r-') What is happening when we fit data? The data are passed as column arrays, x'and y'to the program. Since we’ve typed the data in as row arrays, we have to add the tick (or prime) to transpose the row into a column. (I would think that Matlab would know how to fit either column data or row data, but it chooses to work only with columns which are Page 7 much more common if the data has been imported as explained in the next section.) The initial values for a, b, and c are used to get the fitter started safely. The fitter then computes the difference between the function and the data and adjusts the a,b, and c parameters until this difference is as small as possible. The Matlab output from the fit is: fittedmodel = General model: fittedmodel(x) = -sqrt(a^2-(x-b).^2)+c Coefficients (with 95% confidence bounds): a= 26.62 (18.39, 34.85) b= 1.714 (-0.5507, 3.978) c= 26.55 (18.56, 34.54) Notice that the values a, b, and c, are given along with a range to indicate their 95% confidence interval. This range is very nearly twice as big as the 1-sigma uncertainty that we want. To get the 1-sigma error bars, we want the 68.27% confidence bounds. To extract the coefficients and 1-sigma intervals, you can use the methods: params = coeffvalues(fittedmodel) ranges = confint(fittedmodel,0.6827) You’ll need to convert these into the form a ± d a in your lab reports. If the uncertainty +d a is significantly asymmetric then you can write it a-d a . In this case a = 27± 4 . Selecting Data: Detectors usually have bias or loss of efficiency that complicates data analysis. If you need to select part of your data for some reason, use the find function: selected = find(x<0 & y>0); errorbar(x(selected),y(selected),ey(selected),'.b') This removes the biased point at x=0, y=0 from the analysis. The fit can also be applied to just the selected data: hold on % fit the data fittedmodel = ... fit(x(selected)',y(selected)',fun,'StartPoint',[15 0 15]) % plot the result plot(fittedmodel,'r-'); What’s the difference in the fit? Importing Data Lots of our equipment will collect thousands of data points for you very quickly. These cannot be typed into Matlab by hand. Thank goodness we have computers to automate these tasks. It’s pretty interesting that almost all of the undergraduate theory curriculum Page 8 was developed before computers were invented! How did the old timers do it? Imagine having only graph paper and pen for your experiments. The first utility to try for just about any type of file, txt, csv, xls, jpg, png is importdata(). Both txt and csv are human readable because you can just type the file to the screen. Excel files are labeled xls. Image files are jpg, png, or a few other types. We’ll import a data sample from the LoggerPro that you used in the PHYS-133 lab. Copy the file cia_file1.txt from the desktop to your personal work directory. You can import the data in Matlab: experiment = importdata('cia_file1.txt') Here’s the Matlab output from this command: experiment = data: [100x2 double] textdata: {6x1 cell} The data are in an array: experiment.data that has 100 data points in 2 columns. The descriptive data at the top of the file are in the textdata. Here’s a look at the descriptive data. experiment.textdata = '% Vernier Format 2' ' KIN2D4.cmbl 4/13/07 4:42 PM .' ' Latest' ' Time Position ' 't x ' 's m ' The time in seconds is in the first column and the position in meters is in the second column. Let’s create some variables with physics sounding names to simplify our life. t = experiment.data(:,1); x = experiment.data(:,2); plot(t,x,'.b') Recall the use of “:” to include all the elements in a particular column. Got a problem importing a data file? If you come across a file that puts all the data into the textdata structure instead of into the data array, try using the ‘Headerlines’,N option to tell the importer where to start looking for the data. There are three other functions that are sometimes useful if importdata won’t read the file you need to analyze. The textread or textscan functions can be used to do a formatted read of a txt or csv file. Similarly, xlsread(‘filename.xls’) has more options specific to Excel files. I have had trouble with Excel files that are from a recent Page 9 version of Microsoft! Matlab can’t always keep up with Microsoft’s proprietary file structures. It’s safest to save your data as csv files for analysis. There is a GUI for importing data too. Click on “File” and select “ImportData”. You will be able to select a file like filename.csv and then a GUI will show you the “data” in the file. This might be good for checking out what’s in files, but it can’t be added to a script, so I don’t recommend it for your analysis. Exercises 1) Plot r 2 = (x - xo )2 + (y - yo )2 with: a) r =1, xo =1, yo = 2 in blue, and, b) r = 2, xo =1, yo = 2 in red. Both circles should be on the same plot. 2) Import the file dataToFit.csv using the command ``csvread”. Fit y = ax + b to the data. What are your values for a and b? Page 10