Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a constant to fminsearch

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

like image 992
sooprise Avatar asked Feb 18 '23 20:02

sooprise


2 Answers

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.

like image 192
Andrey Rubshtein Avatar answered Feb 27 '23 14:02

Andrey Rubshtein


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.

like image 33
bla Avatar answered Feb 27 '23 16:02

bla