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

1 view (last 30 days)
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)
% more computations with p and q
P=[p q p*q];
Q=[q p p/q];
function f=second_func(x)
f=norm(PQ); %some dummy operation here for representation. The actual operation is a matrix calculation
function ct=third_func(x)
ct=PQ(2,1); %some dummy operation here for representation. The actual operation is a matrix calculation
The above code block represents the function file and the following code block represents the script i am running to execute the function file.
[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
Suhas Raghavendra Kulkarni
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?

Sign in to comment.

Accepted Answer

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);
function ct = third_func(x) % what is x used for?
ct = PQ(2,1);
Note that your THIRD_FUNC does not return two arrays as the GA documentation requires:

More Answers (0)

Community Treasure Hunt

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

Start Hunting!