Passing a constant to fminsearch

我们两清 提交于 2019-12-05 02:06:37

问题


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!!!


回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!