# Obtain multiple function handles as outputs from one single function for optimisation.

2 views (last 30 days)
Edited: Stephen23 on 3 Mar 2022
Hello,
I am in the process of writing a code for an optimisation problem. However, I am stuck with the following problem.
%% Function that generates the cost function and constraint
function [obj_func, constraint]=functiongenerator(a,b,c)
% parameters a, b and c are passed to this function from anotherscript. They are scalar values
[obj_func,constraint]=first_func; %% THIS IS THE LINE OF CONCERN %%
function [fun, cons]=first_func(x)
p=a*x(:,1);
q=b/c*x(:,2);
% more computations with p and q
P=[p q p*q];
Q=[q p p/q];
PQ=Q-P;
fun=@second_func;
cons=@third_func;
function f=second_func(x)
f=norm(PQ); %some dummy operation here for representation. The actual operation is a matrix calculation
end
function ct=third_func(x)
ct=PQ(2,1); %some dummy operation here for representation. The actual operation is a matrix calculation
end
end
end
The above code block represents the function file and the following code block represents the script i am running to execute the function file.
a=10;
b=15;
c=20;
[obj_func, constraint]=functiongenerator(a,b,c)
xval = ga(obj_func,2,[],[],[],[],[],[],constraint);
However when I run this code, I get the error that
---not enough input arguments in "THE LINE OF CONCERN"---
The above code is only for representation. My actual problem involves matrix multiplications.
How would I be able to execute my code? Any help is much appreciated.
Thank you
##### 2 CommentsShow 1 older commentHide 1 older comment
Thank you for that comment Stephen. Your explanation adds the necessary infromation to complete my actual question. The array "x" being used by "first_func" is, like you rightly assumed, the array of variables being optimised.
How would I then be able to formulate this function to address the error?

Stephen23 on 3 Mar 2022
Edited: Stephen23 on 3 Mar 2022
Get rid of FIRST_FUNC.
Move all of the code that depends on x to SECOND_FUNC.
Something like (untested, but should get you started):
function [fun,cons] = functiongenerator(a,b,c)
PQ = []; % ensure that PQ is passed between nested workspaces: "See also" below.
fun = @second_func;
cons = @third_func;
%
function f = second_func(x)
%
p = a * x(:,1);
q = b/c * x(:,2);
% more computations with p and q
P = [p q p*q];
Q = [q p p/q];
PQ = Q-P;
%
f = norm(PQ);
end
%
function ct = third_func(x) % what is x used for?
ct = PQ(2,1);
end
%
end
Note that your THIRD_FUNC does not return two arrays as the GA documentation requires:

### Categories

Find more on Solver Outputs and Iterative Display in Help Center and File Exchange

R2021b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by