How can I use a 'fitobject' within a function?
7 views (last 30 days)
Show older comments
Hi,
I have created a fitobject from my data like this:
f1 = fit(x, y, 'nearestinterp')
I now want to use f1 within the objective function of an optimization problem and treat it as I would any other function. Assume f is the objective function, I would need to use f1 in a way similar to this: min f = f1(x)*x . However, with f1 being part of the workspace, on execution of the fmincon function I get this error: "Undefined function 'f1' for input arguments of type 'double'."
Is there a way to use f1 in the objective function?
Thanks!
0 Comments
Answers (1)
Philip Caplan
on 14 Apr 2015
You can pass additional parameters to your objective function by creating an anonymous function. Below is an example of passing a fit object to an objective function, subsequently passed to "fmincon".
% Create x = [-1,1] and y some sampled function
x = linspace(-1,1,25);
y = (x-1).^2 +1;
% Fit the samples
f1 = fit(x',y','nearestinterp');
yfit = f1(x);
% Modify the fit to create the objective function
obj = @(x) f1(x)'.*x.^2;
% Solution should be ~0 since we are bracketing [-1,1]
sol = fmincon(obj,1,[],[],[],[],min(x),max(x));
disp(sol);
figure;
hold on
plot(x,y,'o');
plot(x,yfit);
plot(x,obj(x));
legend('Original','Fitted','Modified');
The original function is:
y = (x-1).^2 +1
which is well represented by "fit". An anonymous function then modifies this fit to be
y = ((x-1).^2 +1).*x.^2
Since the fit is defined on [-1,1] (in the example), be careful with the upper & lower bounds passed to "fmincon". There are other ways of passing parameters, which are described at
0 Comments
See Also
Categories
Find more on Linear and Nonlinear Regression in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!