简体   繁体   中英

Multiple Output of Anonymous Function (Function Handler) in MATLAB

I have a function "myFunction" that computes the value and the gradient of a certain quantity. I want to maximize this quantity; since I will use fmincon, I want to pass to fmincon -myFunction. The issue is that myFunction returns also the gradient, ie it should be used as

valueFunction, gradientFunction = myFunction(point)

And gradientFunction will be used by fmincon to compute the minimum. So what I would like to have is have a function that returns -valueFunction, -gradientFunction. But if I define

k=@(x) -myFunction(x) 

matlab raises the error

Error using - 
Too many output arguments

So how to create a function that returns all the outputs of another function, with the opposite sign?

Since negating a function is equivalent to multiply is by -1 you should also negate the function which calculates the gradient.

Now, you real problem is that you need to output 2 variables for a function handler.

You can do something as described in here - Multiple Outputs .

Another option is to create a new function - NegateMyFunction() :

function [valueFunction, gradientFunction] = NegateMyFunction( x )

valueFunction, gradientFunction = myFunction(x);
valueFunction = -valueFunction;
gradientFunction = -gradientFunction;

end

Use that for fmincon .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM