Also, I would like to add that after I run the code, it probably stops after one iteration where only only one set of values of Kp, Ki, Kd are shown and in the Simulink, it shows that Variable 'Kp' (or Ki or Kd) has been deleted from base workspace.
Invalid setting in 'Model' for parameter 'Gain'.
10 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1745346/image.png)
function objective_func = F3(x)
Kp=x(1)
Ki=x(2)
Kd=x(3)
mdl = "Model";
open_system(mdl)
in = Simulink.SimulationInput(mdl)
out = sim(in)
simout = out.J(3001) %objective function value
objective_func=simout;
end
2 commentaires
Réponses (2)
Divyajyoti Nayak
le 6 Août 2024
Hi @SM, from my understanding you are calling the ‘F3’ function iteratively and based on the output from the function changing the gains and passing them in the next call of the ‘F3’ function. Since, the input to the function is a vector, I am also assuming that outside the function the gains are stored in a vector and this could be the source of your issue. Simulink cannot access variables that are used inside functions as they are part of the function workspace not the base workspace. To fix this you can move the definitions of ‘Kp’,’Kd’ and ‘Ki’ from the function to before the function call in the loop. This will populate these values in the base workspace for the Simulink model to use.
gains = [1, 1, 1];
for i = 1:10 %dummy loop
%calculate gains
%Define Kp, Kd, Ki for model to use
Kp=gains(1);
Ki=gains(2);
Kd=gains(3);
%Call F3 to get objective function
objective_func = F3();
end
function objective_func = F3()
mdl = "Model";
open_system(mdl)
in = Simulink.SimulationInput(mdl)
out = sim(in)
simout = out.J(3001) %objective function value
objective_func=simout;
end
Hope this helps!
0 commentaires
Paul
le 6 Août 2024
Hi SM,
function objective_func = F3(x)
mdl = "Model";
open_system(mdl)
in = Simulink.SimulationInput(mdl)
in = in.SetVariable('Kp',x(1));
in = in.SetVariable('Ki',x(2));
in = in.SetVariable('Kd',x(3));
out = sim(in)
simout = out.J(3001) %objective function value
objective_func=simout;
end
0 commentaires
Voir également
Catégories
En savoir plus sur PID Controller Tuning dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!