How to use fittype and fit to get a logarithmic fit to some data

108 views (last 30 days)
Hi, I am trying to get a logarithmic fit to some data I have. To do this, I am currently attempting to use the 'fittype' and 'fit' functions to get the fit, but I keep getting errors. Any help or suggestions would be helpful, including if you suggest using a different method to get the fit. My code and error messages are listed below:
data = fopen('ABC_Domain.txt');
time = fopen('Time_File.txt');
y = fscanf(data, '%f');
x = fscanf(time, '%f');
myfittype = fittype('a+b*log(x)');
[a,b] = fit(x,y, 'logfit')
fclose(data);
I get errors:
??? Error using ==> fittype.fittype>iCreateFromLibrary at 385 Library function mytype not found.
Error in ==> fittype.fittype>fittype.fittype at 311 obj = iCreateFromLibrary( obj, varargin{:} );
Error in ==> fit at 152 model = fittype( fittypeobj, 'numindep', size( xdatain, 2 ) );
Error in ==> ABC_Model_Extension at 12 [a,b] = fit(x,y, 'mytype');
Again, any help would be much appreciated.

Answers (2)

Kevin Claytor
Kevin Claytor on 7 Sep 2012
You may need to supply additional parameters to the fyttype object, otherwise it doesn't know what variables it can vary, and which is the independent variable. Also in your code above, you don't actually use the fit you just created. Here's an example;
x = linspace(1,100)
y = 5 + 7*log(x);
myfit = fittype('a + b*log(x)',...
'dependent',{'y'},'independent',{'x'},...
'coefficients',{'a','b'});
fit(x',y',myfit)

Tom Lane
Tom Lane on 9 Sep 2012
If you want to fit y as a linear function of log(x), you can just apply linear methods. For example, here's how to use backslash:
>> x = rand(20,1);
>> y = 2 - log(x);
>> [ones(size(x)),log(x)]\y
ans =
2.0000
-1.0000
You could also use the fit command with a poly1 fit by supplying log(x) as the predictor.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!