Passing a constant to fminsearch

假如想象 提交于 2019-12-03 16:23:09

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.

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