it's the year 2010 and i finally figured out the fit.m function. why is this awesome? because it takes the place of the tedious excel fits i've used for over a decade. how many hours of my life have i spent clicking the chart button, scatter plot button, fit trendline, power fit, show equation, show R^2? very inefficient! so here is a way that i like much better*:
x and y are your vectors holding your x_i and y_i
A simple linear fit (polynomial order 1):
[cfun, gof, output] = fit(x,y,'poly1')
Finding the exponent of a power law fit:
xlog = log10(x);
ylog = log10(y);
[cfun, gof, output] = fit(xlog,ylog,'poly1')
cfun holds the fit parameters cfun(x) = p1*x + p2, which you can access by cfun.p1 or cfun.p2
gof holds goodness of fit parameters including rsquare and rmse (root mean square error)
output holds other parameters like numobs (# of observations), residuals, and more
i left off the ending semi-colons so the structures will appear automatically
or, you can output these to a text file like so:
fid = fopen('C:\path\filename.txt', 'a+');
% open file for writing, append mode (will create file if it does not exist yet)
fprintf(fid, '%8.3f, %8.3f, %8.3f %8.3e, %d\n', cfun.p1, cfun.p2, gof.rsquare, gof.rmse, output.numobs);
% the different formats used are f = fixed-point 8 digits, 3 decimals, e = exponential notation, d = integer, \n = newline
status = fclose('all');
% close the file properly so you can open it with other programs
this is especially useful when employed in a loop, say, if you want to look at a large data set and then certain subsets of that data, or if you want to look at y versus several different x variables.
here is a list of other fit types.
note/question: with the method above, i get the same power law fit parameters as using excel. there is a power fit option in matlab (instead of taking log10 and doing a polynomial fit) but i don't get the same answers.
now you can
(1) open the text file with wordpad (or other) to inspect
(2) use the file as input for matlab plot
(3) *sigh* open the file in excel as a comma delimited, save to .xls and plot
post questions or improvements to comments.
* i must admit that i probably wasn't using excel to its full capabilities by doing things the tedious way, but i just never learned any cool shortcuts in excel. that says something about me and something about excel.
Sunday, January 17, 2010
Subscribe to:
Post Comments (Atom)
omg i cannot believe you have a blog for matlab. i need to step up my game or will lose this battle! awesome though! -Elowyn
ReplyDeletean online shrine to matlab...
ReplyDelete