Task: Write a script to read the data file introduced in task 5.1. Extract the first (time) and third columns (D2) of the data matrix. Fit exponential and power functions to these values. Plot the original data vs time along with the function fits.
Using the tools from the last task, it is easy to fit polynomials to data. However, there are no tools for fitting other functional forms. If we do a small bit of algebra, we can fit exponentials and power functions with polyfit.
An exponential function has the form:
x(t) = a * exp(b*t)where exp() is the built-in MATLAB function to calculate the exponential (that is, e^x where e is the base of the natural logarithms).
But the natural logarithm (log()) is the inverse function of the exponential. Be aware that there is also log10() which calculates the logarithm using a base of 10 (that is, the common logarithm).
Recall that the log of a product is the sum of the logs of the values being multiplied. So,
log(x(t)) = log(a) + log(exp(b*t))= log(a) + b*tThe path to fitting data to an exponential function is clear; do a linear in t fit to the log of the data:
p = polyfit(t,log(x),1); b=p(1); % recover the fit coefficients a=exp(p(2)); xf=exp(polyval(p,t)); % the fitted exponential values. e=x-xf; % error of the fitwhere xf are the estimated values to compare to the original data.
A power function has the form:
x(t) = c t^dTaking the log of the expression gives
log(x(t)) = log(c) + d*log(t)Again, calculate a linear fit, but take the log of both x and t,
p = polyfit(log(t),log(x),1); d=p(1); % recover the fit coefficients c=exp(p(2)); xf=exp(polyval(p,log(t))); % the fitted exponential values. e=x-xf; % error of the fit
Flow chart for task 5.4
%%% Task 5.4 %%% read data, extract variables %%% fit exponential function to data %%% fit power function to data %%% reconstruct function from fits %%% plot original data and fit curves %%% add legends and title
Here is the script to generate the answer to this task.
%%% Task 5.4 %%% read data, extract variables data=load('fitdata.dat'); time=data(:,1);D2=data(:,3); %%% fit exponential function to data pe=polyfit(time,log(D2),1); %%% fit power function to data pp=polyfit(log(time),log(D2),1); %%% reconstruct function from fits D2e=exp(polyval(pe,time)); D2p=exp(polyval(pp,log(time))); %%% plot original data and fit curves figure plot(time,D2,'k',time,D2e,'r',time,D2p,'b') %%% add legends and title title('D2 (k), exp (r), power(b)') xlabel('time (day)') ylabel('D2')
Here is the figure responding to this task.