5

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

sooprise
  • 22,657
  • 67
  • 188
  • 276

2 Answers2

6

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.

Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
  • Thanks, this is the method I used. – sooprise Oct 18 '12 at 18:30
  • This answer with additional examples is actually included in the official matlab documentation: http://www.mathworks.com/help/matlab/math/parameterizing-functions.html – Ufos Jun 23 '16 at 11:08
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.

bla
  • 25,846
  • 10
  • 70
  • 101