Using function handle in fittype function
6 views (last 30 days)
Show older comments
Hi,
I have this code and it works fine:
z=[5.26;7.58;12.64;15.38;12.64;7.58;5.26];
x=linspace(-pi/2,pi/2,7);
q=2;
g = fittype(@(a0,a1,b1,a2,b2,x) a0+a1*cos(x*q)+b1*sin(x*q)+a2*cos(2*x*q)+b2*sin(2*x*q)); % this is fourier2
[fitobject,gof] = fit(x',z,g,'StartPoint',[0,0,0,0,0]);
However, I want to have all the cofficients in one input argument like the following code:
z=[5.26;7.58;12.64;15.38;12.64;7.58;5.26];
x=linspace(-pi/2,pi/2,7);
q=2;
g = fittype(@(p,x) p(1)+p(2)*cos(x*q)+p(3)*sin(x*q)+p(4)*cos(2*q*x)+p(5)*sin(2*q*x)); % this is fourier2
[fitobject,gof] = fit(x',z,g,'StartPoint',[0,0,0,0,0]);
but I get this error:
Error using fittype>iAssertIsMember (line 1084)
Coefficient p does not appear in the equation expression.
Could you please help me if there is a way to do it this way?
0 Comments
Accepted Answer
Matt J
on 18 Jan 2024
Edited: Matt J
on 18 Jan 2024
No, there isn't. fit and fittype need to know the number and names of the unknown coefficients, and the only way they can do that is to have them listed as individual input arguments in the function signature.
For the problem you've shown, however, you would never use fit(). The model is linear in the unknown parameters and can therefore be solved algebraically as below.
z=[5.26;7.58;12.64;15.38;12.64;7.58;5.26];
x=linspace(-pi/2,pi/2,7)';
q=2;
G = [x.^0, cos(x*q), sin(x*q), cos(2*q*x), sin(2*q*x)]; % this is fourier2
p=G\z
More Answers (0)
See Also
Categories
Find more on Linear and Nonlinear Regression 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!