Biomedical Engineering Reference
In-Depth Information
Appendix 11.A
MATLAB CODE FOR PID OPTIMIZATION
function [Kp,Ki,Kd] = runm %runtracklsq
% RUNTRACKLSQ demonstrates using LSQNONLIN with Simulink.
% runm %model1 %optsim % Load the model
Pid0 = [0.91 0.105 0.1];% Set initial values
a1 = 21.3; a2 = 1; % Initialize plant variables in model
options = optimset('LargeScale', 'off', 'Display', 'iter', ...
'TolX',0.001 , 'TolFun', 0.001);
pid = lsqnonlin(@tracklsq, pid0, [], [],options);
Kp = pid(1); Ki = pid(2); Kd = pid(3);
function F = tracklsq(pid)
%Track the output of optsim to a signal of 1
%Variables a1 and a2 are needed by the model optsim.
% They are shared with RUNTRACKLSQ so do not need to be redefined here.
Kp = pid(1);
Ki = pid(2);
Kd = pid(3);
% Compute function value
simopt = simset('solver', 'ode14x', 'SrcWorkspace', 'Current');
% Initialize sim options
[tout,xout,yout] = sim('runm',[0 10],simopt);
F = yout-1;
end
Kp = pid(1)
Ki = pid(2)
Kd = pid(3)
%model1
end
The function ' runtracklsq ' sets up all the required values and then calls ' lsqnonlin '
with the objective function ' tracklsq ,' which is nested inside ' runtracklsq .' The variable
options passed to ' lsqnonlin ' define the criteria and display characteristics. In this case
the medium-scale algorithm is used, and termination tolerances for the step and objective
function are given on the order of 0.001.
To run the simulation in the model ' optsim ,' the variables a 1 and a 2 ( a 1 and a 2 are
variables in the Plant block) must all be defined. K p , K i ,and K d are the variables to be
optimized. The function ' tracklsq ' is nested inside ' runtracklsq ' so that the variables a 1
and a 2 are shared between the two functions. The variables a 1 and a 2 are initialized in
' runtracklsq .'
The objective function ' tracklsq ' must run the simulation. The simulation can be run
either in the base workspace or the current workspace, that is, the workspace of the
function calling ' sim ,' which in this case is the workspace of ' tracklsq .' In this example,
the ' simset ' command is used to tell ' sim ' to run the simulation in the current workspace
by setting ' Src Workspace 'to' Current .' A solver for ' sim ' can be also chosen using the
Search WWH ::




Custom Search