How to control simulink with fmincon using 2 (two) decision variables

I have a simulink file that I want to control. I want to minimize my objective:
function q = obj(cr,tr) % cr, tr are the variables that I want to be manipulated
sopt = simset('solver','ode3','SrcWorkspace','base','DstWorkspace','base','SaveFormat','Array');
[~,~,yo]= sim('sgs2.slx',[0 10], sopt);
q=abs(yo(end,1)-yo(end,2));
end
I call fmincon
x=fmincon(@obj,xo,[],[],[],[],xmin,xmax,[],options);
the optimization runs but fails.
I think that the way that passing the decision variables is wrong but I have no idea what to try.

Answers (1)

Hi,
do you have other variables in your model apart from cr and tr? If not, you should select 'current' for SrcWorkspace and DstWorkspace. This way Simulink would grab the variables cr and tr from the input variables.
Second: your objective function needs to be declared differently. It must have the form obj(x) where x is a vector (of size two in your case). So you would need to change
function q = obj(x)
cr = x(1);
tr = x(2);
Titus

4 Comments

Thanks for the response Titus, I changed the value of SrcWorkspace and DstWorkspace to 'current' and the optimizer does not runs. Changed the objective to:
function q = obj(z)
cr=z(1);
tr=z(2);
sopt = simset('solver','ode3','SrcWorkspace','base','DstWorkspace','base','SaveFormat','Array');
[~,~,yo]= sim('sgs2.slx',[0 10], sopt);
q=abs(yo(end,1)-yo(end,2));
end
It runs well but with wrong results.
I'm trying to make the optimizer to try different values for cr and tr so the objective can be minimized. Maybe I'm wrong where the optimizer "communicates" with the simulink file.
Finally figure out what was wrong. I was running an extra simulation and this was confusing the optimizer. Thanks for your help.
By the way do you have any idea why the optimizer tries the same values for the variables three times before the next try ?
Yes, I do: the values are not exactly the same, but very similar. For the jacobian it computes the finite differences
df/dcr ~ (f(cr+h, tr)-f(cr,tr))/h
and
df/dtr ~ (f(cr, tr+h)-f(cr,tr))/h.
So you see three (similar but not equal) calls to f for each iteration. More generally, for n variables you need n+1 function evaluations per iteration (neglecting the fact that the optimizer sometimes updates the jacobian without recomputing it).
Titus
Thank you very much for the information.

This question is closed.

Asked:

on 13 Nov 2014

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!