from predve.m by Hanna Aboukheir
State Space Predictive Control

[K,L]=predve(A,B,C,D,l,tt)
function [K,L]=predve(A,B,C,D,l,tt)
% --------------------------------------------------------------------
%  This is a m-file that calculates a discrete predictive controller 
%  using a State Space Approach 
%
%           [K,L]=predve(A,B,C,D,l,tt)
%           
%           Where:
%           A,B,C,D: Discrete State Space Representation of plant
%           l:    Lambda 
%           tt:   Sampling Period
%           L:    Predictive Controller (Feedforward)
%           K:    Predictive Controller (Feedback) 
%
% Only works on fully controllable and observable plants
% Developed by: Hanna Aboukheir                  Hanna2k2@hotmail.com
%
% Part of Advanced Process Control Toolbox.
% --------------------------------------------------------------------

% Controller Parameters
closereq;
fi=obsv(A,C);
fh=ctrb(A,B);
if any(rank(fi)<length(A)),error('The plant is not observable'),end
if any(rank(fh)<length(A)),error('The plant is not controllable'),end
rr=rank(fi);
n1=0;
n2=rr-1;

% Predictive Controller Design
for i=n1:n2
   H(i+1)=C*A^i*B;
end
f=n2+1;
G=H(1:f)';
G=diag(G);

% Building Triangular L matrix
e=tril(ones(length(G)));
G=G*e;
[f,c]=size(G);
clc;
L=(inv(G'*G+l*eye(c)))*G';

% Gain of the Controller 
K=L*fi;
K=[K(1:length(K))];
L=L';
L=[L(1:length(L))];

% Step function of closed loop plant
[num,den]=ss2tf(A-B*K,B*L,C,D*L,1);
gs=tf(num,den,tt);
step(gs,'b');
title('Step Response For Predictive Controller')
clc

Contact us at files@mathworks.com