function [sys P Et Po Pc output] = opttime(sys,modal,varargin)
%OPTTIME Computes a local time optimized OCLP for a given OCCD system.
%
% [OSYS,P,Et,Pctr,Po] = OPTTIME(SYS) where SYS is the structure array (as
% if created by OCSET), returns:
% OSYS is the same as SYS, but now with the optimal open and
% closed-loop parameters and the locally optimal terminal time.
% P is the time optimized performance.
% Et is the terminal energy.
% Po is the open-loop energy.
% Pc is the closed-loop energy.
%
% [OSYS,P,Et,Pctr,Po] = OPTTIME(SYS,modal) returns the performance in
% each mode rather than total performance.
%
% OPTTIME(SYS,modal,P1,V1,P2,V2,...) uses the given parameter-value pairs
% in options used in the call to FMINSEARCH.
%
% [OSYS,P,Et,Pctr,Po,output] = OPTTIME(...) gives the output structure
% returned by the call to FMINSEARCH.
%
% OPTTIME uses the values in SYS.CP, SYS.CD, and SYS.TO as intial guesses.
if nargin<2
modal = false;
end
% Set default options
opt = optimset('TolX',1e-1,'TolFun',1e-5,'disp','none','MaxFunEvals',300);
if nargin>3
% Apply given parameter/value pairs
opt = optimset(opt, varargin{:});
end
Xo = sys.To;
if any(sys.Type == [1 2 4 5])
% Has P control
Xo = [Xo;sys.cp];
else
sys.cp = 0;
end
if any(sys.Type == [2 3 5 6])
% Has D control
Xo = [Xo; sys.cd];
else
sys.cd = 0;
end
if ~any(sys.Type==[1 2 3 7])
%Has open-loop control
sys.a = zeros(size(sys.xo));
sys.b = zeros(size(sys.xo));
end
% Compute optimal closed-loop parameters and terminal time
[C ignore ignore output] = fminsearch(@(X)OOLPx(X, sys), Xo,opt);
sys.To = C(1);
if any(sys.Type == [1 2 4 5])
sys.cp = C(2);
end
if any(sys.Type == [2 3 5 6])
sys.cd = C(end);
end
% Compute corresponding optimal open-loop performance and parameters
if any(sys.Type==[1 2 3 7])
[sys P Et Po Pc] = oolp(sys,modal);
else
[P Et Po Pc] = performance(sys,modal);
end
function P = OOLPx(C, sys)
% Objective function for optimization
sys.To = C(1);
if any(sys.Type == [1 2 4 5])
sys.cp = C(2);
end
if any(sys.Type == [2 3 5 6])
sys.cd = C(end);
end
if any(sys.Type==[1 2 3 7])
[ignore P] = oolp(sys);
else
P = performance(sys);
end