3 views (last 30 days)

I have a function of the following form

function [out1, out2] = demo_fcn( in )

out1 = in(1);

out2 = in(2);

end

which gets called by

[out1, out2] = @(x) demo_fcn(x);

but anonymous functions are not allowed more than one outputs. This is clearly a simplified example, the application is for a nonlinear programming problem where out1 is the objective function and out2 is the gradient calculation. I am not sure how I can structure this differently or in a way which is acceptable by MATLAB syntax.

Note the error messge is

Only functions can return multiple values.

Star Strider
on 10 Dec 2019

One option is to have the two outputs to one vector, then separate them in a subsequent assignment:

demo_fcn = @(in) [in(1) in(2)];

in = rand(2,1)

Out = demo_fcn(in)

Out1 = Out(1)

Out2 = Out(2)

This works, however I cannot tell if it does what you want it to do.

Star Strider
on 10 Dec 2019

O.K.

The approach I used would clearly not allow concatenation such as that unless the outputs of the two sub-functions were in cell arrays. That adds the additional complication of recovering the double array from the cell array, however that is not diffcult.

I encourage you to experiment with that approach.

Sign in to comment.

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 3 Comments

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/495945-multiple-outputs-from-anonymous-function#comment_776600

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/495945-multiple-outputs-from-anonymous-function#comment_776600

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/495945-multiple-outputs-from-anonymous-function#comment_776612

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/495945-multiple-outputs-from-anonymous-function#comment_776612

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/495945-multiple-outputs-from-anonymous-function#comment_776649

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/495945-multiple-outputs-from-anonymous-function#comment_776649

Sign in to comment.