Fitting to a line with Matlab

Back

First enter some data, and plot it.

>> x=[0 2.6 5.1 7.4 9.6 7.8 4.8 2.6 0.1];
>> y=[-0.3 23.5 51.9 70.1 98.2 82.9 46.0 28.6 4.8]/1000;  %Convert to amps from mA.
>> plot(x,y,'o');  %Plot data with circles
>> title('Verifying Ohms Law');
>> xlabel('Volts');
>> ylabel('Current (Amps)');

Go to Tools->Basic Fitting and set dialog box as below

Hit the right arrow at the bottom of the box.

The figure now looks as shown.

Since the slope is about 0.01, the resistance is about 100 ohms.

It is also possible to use Matlab do the curve-fit and then calculate the correlation coefficient.  In the following code "p" contains coefficients of linear, or first order, fit (slope=m=p(1)=0.0100, intercept=b=p(2)=0.006).

>> p=polyfit(x,y,1)   
p = 0.0100 0.0006 
>> R=corrcoef(x,y);
>> R(1,2)
ans =
    0.9961

A correlation coefficient with a magnitude near 1 (as in this case) represents a good fit.  As the fit gets worse, the correlation coefficient approaches zero.


  email me with any comments on how to improve the information on this page (either presentation or content), or to let me know if you had any particular difficulties with this lab.
You may use any portion of this document for your lab report, but be sure to reference it.

Back