1
votes

So, I've fitted an exponential curve to some data points using 'fit' and now I want to get the equation of the fitted curve in the Legend in the graph. How can I do that? I want to have an equation on the form y=Ce^-xt in the legend. Can I get the coefficients, C and x from the fitted curve and then put the equation inside the legend? Or can I get the whole equation written out in some way? I have many plotted graphs so I would be grateful if the method is not so much time consuming.

Edit: Perhaps I was unclear. The main problem is how I should get out the coefficients from the fitted line I've plotted. Then I want to have the equation inside the legend in my graph. Do I have to take out the coefficients by hand (and how can it be done?) or can Matlab write it straight out like in, for example, excel?

3
you can take a look to my answer here: legend with fit-fcnLucius II.
That's the question I posted yesterday and I have done all that :P. Take a look at my edit and perhaps you'll understand my question.Djamillah
I see :) and there are two good answers already :oLucius II.

3 Answers

3
votes

The documentation explains that you can obtain the coefficients derived from a fit executed as c = fit(...), as

coef=coeffvalues(c) 
C=coef(1)
x=coef(2)

You can create your own legend as illustrated by the following example.

Defining C and x as the parameters from your fits,

% simulate and plot some data
t= [0:0.1:1];
C = 0.9;
x = 1;
figure, hold on
plot(t,C*exp(-x*t)+ 0.1*randn(1,length(t)),'ok', 'MarkerFaceColor','k')
plot(t,C*exp(-x*t),':k')
axis([-.1 1.2 0 1.2])

% here we add the "legend"
line([0.62 0.7],[1 1],'Linestyle',':','color','k')
text(0.6,1,[ '               ' num2str(C,'%.2f'),' exp(-' num2str(x,'%.2f') ' t)   ' ],'EdgeColor','k')
set(gca,'box','on')

Example output:

enter image description here

You may have to adjust number formatting and the size of the text box to suit your needs.

2
votes

Here is a piece of code that will display the fitted equation in the legend box. You can reduce the amount of digits in the legend by manipulating the sprintf option: %f to %3.2f for example.

%some data
load census
s = fitoptions('Method','NonlinearLeastSquares','Lower',[0,0],'Upper',[Inf,max(cdate)],'Startpoint',[1 1]);
f = fittype('a*(x-b)^n','problem','n','options',s);

%fit, plot and legend
[c2,gof2] = fit(cdate,pop,f,'problem',2)
plot(c2,'m');
legend(sprintf('%f * (x - %f)^%d',c2.a,c2.b,c2.n));

The command disp(c2) will display in the command window what is stored in the fit object. Also, by enabling the "datatip in edit mode" option (Matlab preferences, then Editor, then Display), you will have an instant view on the data stored by putting your mouse cursor over an object.

0
votes
function [S]=evaFit(ffit)
  S=sprintf('y=%s',formula(ffit));
  S2='';
  N=coeffnames(ffit);
  V=coeffvalues(ffit);
  for i= 1:numcoeffs(ffit)
      S2=sprintf('%s %c=%f',S2, string(N(i)), V(i));
  end
  S=sprintf('%s%s',S, S2);
end