error Function definitions are not permitted in this context
1 view (last 30 days)
Show older comments
This is my homework:
Use a least squares fit of this data to obtain values for A and Ea for the reaction k = Aexp(−Ea/RT)
So I wrote:
% --- Store data
r=8314; % gas constant, J/(K*kg-mol)
t=[773.5 786 797.5 810 810 820 834];
k=[1.63 2.95 4.19 8.13 8.19 14.9 22.2]*1e-3;
% --- Obtain fit, print parameters, and plot fit along with data
[a,ea]=fitArrhenius(k,t,r);
tf=linspace(750,840);
kf=a*exp(-ea./(r*tf));
plot(t,k,'o',tf,kf,'-');
xlabel('T (K)'); ylabel('Reaction rate'); legend('Data','Fit',2);
% =====================================================
function [a,ea] = fitArrhenius(k,t,r)
% fitArrhenius Least squares fit to parameters of arrhenius rate equation
if nargin<3, r=8314; end % default gas constant J/(K*kg-mol)
c=expfit(1./(r*t),k);
a=c(1);
ea=-c(2);
And at the end a received this:
>> function [a,ea] = fitArrhenius(k,t,r)
function [a,ea] = fitArrhenius(k,t,r)
|
Error: Function definitions are not permitted in this context.
0 Comments
Accepted Answer
Walter Roberson
on 11 Feb 2014
You cannot define functions at the command prompt. You need to store them in files. In this case you would need to store into fitArrhenius.m
0 Comments
More Answers (1)
Joseph
on 12 Feb 2014
- According to the documentation "expfit" does a maximum likelihood fit assuming the error follows an exponential distribution.
- A true least squares method would involve using Newton's method to minimize the function: sum(I=1:7,(kf(t)-k)^2) with respect to a and Ea.
- The common way of doing this (what Excel does) is linearize the formula by taking the natural log of both sides and then doing a least squares fit to the transformed data, then exponentiating the constant and setting the slope parameter as the exponent. The code for this is shown below (Sorry for extra returns but the preview didn't wrap the text)
close all; clear all; clc;
% --- Store data
r=8314; % gas constant, J/(K*kg-mol)
t=[773.5 786 797.5 810 810 820 834];
k=[1.63 2.95 4.19 8.13 8.19 14.9 22.2]*1e-3;
% --- Obtain fit, print parameters, and plot fit along with data
% Arrhenius equation: k = Ae^(-Ea/(r*t);
% Take ln of both sides
% ln A + Ea*(-1/rt) = ln k
k2 = log(k)';
t2 = -1./(r*t)';
% Set up least squares matrix (see Least Squares on Wikipedia)
X = [ones(1,length(t2))',t2];
% Least squares solution;
param = (X'*X)^-1*X'*k2;
% exponentiate constant since we solved for log a
a = exp(param(1));
ea = param(2);
tf=linspace(750,840);
kf=a*exp(-ea./(r*tf));
plot(t,k,'o',tf,kf,'-');
xlabel('T (K)'); ylabel('Reaction rate');
legend('Data','Fit',2);
0 Comments
See Also
Categories
Find more on Interpolation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!