How can I pass a constant to fminsearch? So like, if I have a function:
f(x,y,z), how can I do an fminsearch with a fixed value of x?
fminsearch(@f, [0,0,0]);
I know I can write a new function and do an fminsearch on it:
function returnValue = f2(y, z)
returnValue = f(5, y, z);
...
fminsearch(@f2, [0,0]);
My requirement, is I need to do this without defining a new function. Thanks!!!
You can use anonymous functions:
fminsearch(@(x) f(5,x) , [0,0]);
Also you can use nested functions:
function MainFunc()
z = 1;
res = fminsearch(@f2, [0,0]);
function out = f2(x,y)
out = f(x,y,z);
end
end
You can also use getappdata
to pass around data.
One way I can think of is using a global variable to send the constant value to he function, this is in the level of the function you use. For example
in your function file
function y = f(x1,x2,x3)
% say you pass only two variables and want to leave x3 const
if nargin < 3
global x3
end
...
then in the file you use fminsearch you can either write
y=fminsearch(@f,[1 0 0]);
or
global x3
x3=100 ; % some const
y=fminsearch(@f,[1 0]);
It would be interesting to see other ways, as I'm sure there can be more ways to do this.
来源:https://stackoverflow.com/questions/12874317/passing-a-constant-to-fminsearch