Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

Homework #6: Fitting

Physics 281L

In this assignment you will write and use a weighted linear least squares fitting function in MATLAB. You will then gain some experience with exponential fitting.

This is a two-step assignment. You will complete section 1 during class in groups. Once your instructor has checked that your code works, you will be sent the code necessary to complete the rest of the assignment on your own time.

1    Write a Linear Least Squares Fitter (To Be Completed in Pairs)

Earlier in the course (during the MATLAB tutorial) you wrote an unweighted linear least-squares fitter. Now you will write a weighted linear least-squares fitter. You will begin by writing your own MATLAB function that simply calculates m and b (without worrying about the uncertainties in m and b yet). MATLAB contains many built-in functions such as mean() and factorial(), but you can also write your own functions. Your task is to write a LinFit() function which you will be able to use in future scripts just as you would use mean and factorial.

1. In MATLAB, create a new function called “LinFit,” and set the inputs to be the x  and y  data, and the uncertainties in the y data.  Set the outputs to be the slope and y-intercept. The syntax is given on the top line of Fig. ??.

 

Figure 1:  Skeleton of the LinFit function you will write. Replace the green comments with your code.

2. Using Fig.1 as a guide, write code to calculate m and b . The following equations derived in class may help. To eliminate the need for numerous for-loops, you may consider using the dot product function instead. Recall that ⃗a ·  =  i ai bi .

m =  

 !

 !

 !

i=1  σi(2) !#

(1)

b =    !    !   !    !# D =   !    !   !2

(2)

(3)

3. Download the WeightedLinearFittingActivity .m script from Sakai  (it is available both via this homework assignment and in MATLAB Resources/Fitting folder). This script contains data from the Lab 0 diffraction grating experiment.  With your LinFit function in the same directory (or properly added to the path), run WeightedLinearFittingActivity.m. Use the resulting linear fit to determine the line spacing (1/a) of the diffraction grating.

4. For comparison, also calculate the line spacing using an unweighted linear least-squares fitter (such as Excel or LinFit with all uncertainties set to 1).  If the results differ, discuss specifically  why one is larger than the other. Which value of 1/a do you trust more? To answer this question, look closely at the two fits, and note which data points each trendline gets closer to.

5.  Check Your Work:

❼  When you have completed the above steps, call over your instructor.

❼  Demonstrate to them that your LinFit function can be used to find 1/a .

❼  Also show them the line spacing you found using the unweighted fitter.

❼  If the results differ, explain to your instructor why that is, and specifically why one is bigger than

the other.

6.  Optional:  If you have extra time, update LinFit to perform uncertainty calculations.

2    Explore the Full-Featured LinFit Function (Individual)

Once you have completed section 1, your instructor will provide you with another version of LinFit. This version has the same basic functionality as yours, but contains many more features.  It can calculate the uncertainty in m and b due to both the quality of the fit and the uncertainty in each data point. The syntax for this function is

[m,b,sigma m,sigma b,r2]  =  LinFit(X,Y,sigmaY,calc type)

where the additional argument, calc type, may be set to any of the three following strings:‘Data’,‘Quality’, or‘Combined’.  Note that the single quote marks must be included.  These strings specify how uncertainty should be calculated (based on uncertainty in the y data, based on the quality of the fit, or both, respectively). The function outputs uncertainties in both m and b along with the R2  value of the fit. You are free to use this function for all future labs.

1. Look through the new LinFit function and read the comments to gain a feel for how it works. Note that the function begins with a lot of error checking steps which end execution of the code, and provide helpful messages to the user should a mistake such as differing numbers of x and y values be made.

2. Use the new LinFit function to calculate the uncertainty in diffraction grating line spacing using the ‘Data’,‘Quality’, and‘Combined’methods (i.e. run the code 3 times).

3. Answer the following questions in the text submission box for this assignment on Sakai: What percent of the variance (uc(2)) in 1/a is due to the quality of the fit, and what percent is due to

uncertainty in the data? Does this make intuitive sense? Present evidence in support of your answer.

4. Upload a png, pdf, tif, or jpg image of your fit to the Sakai Assignment.  Be sure to use the print function to directly export the plot at 300 dpi or greater no screen shots, low-resolution images, or .fig files!

3    Exponential Fitting of Decay Data with an Offset (Individual)

All of you have experience fitting straight lines in Excel, and some facility with translating problems into forms that can be fit with simple straight line models. For example if you want to analyze a decay

V (t) = V0 e t/τ ,                                                                                         (4)

you know to take the logarithm of both sides to get

ln(V (t)) = − t + ln(V0 ),                                                                               (5)

which is a straight line in t .  But a much more common problem is where the decay is not to zero but to some other equilibrium value V1 , so that

V (t) = V1 + V0 e t/τ .                                                                                    (6)

This equation now has three unknowns: τ , V0 , and V1 . Thus, the “trick”of taking the log of both sides fails (and so will Excel, as you can show by trying to fit Decay 2 .csv there).

The data in Decay 1 .csv and Decay 2 .csv are voltages relative to an arbitrary “ground.”In other words, data may be shifted vertically such that it asymptotes to some value above or below the horizontal axis known as the DC offset,” so we have the situation mentioned above in Eq.6.

1. Import the data from Decay 1 .csv into MATLAB as two column vectors: t and V. Plot the data.

2. Create a script that linearizes this data in accordance with Eq.5 and finds best-fit values for τ  and V0  using LinFit. This should work just fine. If you would like, you can check the resulting τ  and V0 values using an exponential fit in Excel.

3. Import the data from Decay 2 .csv into MATLAB as two column vectors: t and V. Plot the data.

4. Attempt to generate a fit using the same code you used for Decay 1 .csv.

5. Answer the following questions in the text submission box for this assignment on Sakai: What happened when you tried to linearize and fit this data?  If this approach failed, how and why did it fail? Do you have any ideas for how this problem could be fixed? Can Excel help? (Remember that in a real-life situation, you generally will not know the value of V1 )

For the purposes of this class, rather than writing our own exponential fitter, we will use MATLAB’s built-in curve fitting tool.  To access the tool, go to the Apps tab, and select Curve Fitting.”  If the curve fitting app is not installed, press the Get More Apps” button, and install the “Curve Fitting Toolbox.”You can create a fit as shown in Fig.2 by selecting your x and y data, choosing the exponential fitting routine, and setting the number of terms to be 2. This will fit your data to

y(x) = aebx + cedx .                                                                                      (7)

In order to model a constant DC offset, you will need to set either b  or d  to 0 (so that either edx  or ebx becomes 1).  This can be accomplished in the “Fit Options” window by constraining the upper and lower bounds of one of these variables to 0. The fit results will appear in the box on the left.

6. Generate a fit to the Decay 2 .csv data using MATLAB’s curve fitting tool.

7. In the text submission box for this assignment on Sakai, record the best-fit time constant τ, initial voltage V0 , and DC offset V1 .  No uncertainties necessary.

Note  1:  If you would like to see the code that produced the fit, go to File >  Generate Code.  This allows you to incorporate the fitting algorithm into other scripts.

Note  2:  You can use the curve fitting tool to do weighted fits.  Select a matrix of the same dimensions as your x and y data in the “Weights”menu. Be careful though higher values receive higher weight in the fit. Weights should be the square root of the reciprocal of the uncertainties.

 

Figure 2: MATLAB’s Curve Fitting Tool, demonstrating the steps required to fit an exponential to the Decay .csv data.