# optimizing two variables in fmincon with different sizes

12 views (last 30 days)
Romio on 10 Mar 2022
Answered: Walter Roberson on 10 Mar 2022
I have a nonlinear optimization problem where I want to optimize an n x n matrix A and an n x 1 vector b. How can I set up the problem so that fmincon can solve it? Assume that the objective is 0 with no equality or inequality constraints. How can I set up the nonlinear constraint function nonlcon and the inital conditions. How can I get two output from fmincon?

Walter Roberson on 10 Mar 2022
You cannot directly pass two inputs to be optimized to fmincon, and you cannot directly return two outputs from fmincon.
What you should do is create a vector of values, taking either [b, A] or [A, b] and reshaping to a vector. Inside your objective function, extract the appropriate components from the input vector and reshape as needed:
function cost = myobj(x)
b = reshape(x(1:50), [], 1);
A = reshape(x(51:end), 50, 50);
end
Construct your constraints around the same vector configuration.
x0 = reshape([b0, A0], [], 1);
fmincon(@myobj, x0, ....)
I would suggest that in your case, you have a look at Problem Based Optimization, which will automatically do all packing and unpacking for you (but depending on the complexity of your objective and constraints might have some trouble calculating some values.)

### Categories

Find more on Choose a Solver 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