Search code examples
matlabfminsearch

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


Solution

  • 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.