Mat Lab Tutorial V 2
Mat Lab Tutorial V 2
X
1.0000
1.2743
1.6238
2.0691
2.6367
3.3598
4.2813
5.4556
6.9519
8.8587
11.2884
14.3845
18.3298
23.3572
29.7635
37.9269
48.3293
61.5848
78.4760
100.0000
f(X)
1.6523
1.8215
2.0050
2.1106
2.3456
2.4778
2.5952
2.8175
2.8945
3.0125
3.0001
2.9454
3.1056
3.1850
3.2454
3.1170
3.2313
3.2092
3.3027
3.2677
Create a matrix fitData which contains this information. You could use:
>>fitData = dlmread('fitdata.txt', '\t', 1, 0);
Assuming fitdata.txt exists in your working directory. The 1 in the third input tells Matlab the data is
starting on the 2nd row of the text file (Aside: Matlab indexes occasionally start with 0 as in JAVA, but
usually start with 1 you can tell different coders wrote different parts of this software).
Assign the X column to the variable X and the f(X) column to the variable Y, then plot the data with a
semilog plot.
>> X = fitData(:,1);
>> Y = fitData(:,2);
>> semilogx(X,Y, bd)
%bd specifies blue diamond, unconnected data points
We need to provide Matlab with initial guesses for our coefficient values. At this point its a good idea
to plot our function to see if the data makes sense in regards to it. We can start by guessing 1 for both
coefficients; in a real experiment your prior knowledge of what you are measuring would determine
these guesses.
>>hold on
>>semilogx(X, (1 ./(1 + 1*X))
Now lets have Matlab figure out the best fit (least squares sense) of the data to this function, then plot
the data and fit together.
Here we plotted two sets of data in the same command. See the help file for semilogx to understand
how this works. Notice that although our guess wasnt very good, Matlab had no trouble finding good
coefficients. This wont always be the case with more complicated data and functions.
Additional Resources:
MITs MATLAB answer page: http://web.mit.edu/answers/matlab/
Another MATLAB tutorial, with additional material on looping and solving ODEs in MATLAB:
http://openwetware.org/images/7/76/MatlabTutorial2.pdf