  function u = dimc(qnum,qden,rmodvec,uprev)
% discrete IMC -- used in MPC 2013 -- hw3
% b.w. bequette, 18 Sept 2013
%
%   u(z) = q(z) rmod(z)
%           qnum(z)
%   q(z) = --------
%           qden(z)
%   the leading coefficient in the qden polynomial is assumed to be 1
%
%   rmodvec = modified setpoint vector, oriented rmod(k-2), rmod(k-1),
%             rmod(k)   (from top down)
%   uprev   = vector of previous manipulated inputs, oriented
%             uprev(k-2), uprev(k-1) (from top down)
% the numerator and denominator polynomials are oriented in the
%   opposite direction as the modified setpoint and manipulated
%   input vectors, so rback and uback are formed to reverse that
%   order
  rback = rmodvec(length(rmodvec):-1:1);   % reverse order
  uback = uprev(length(uprev):-1:1);       % reverse order
  u = qnum*rback -qden(2:length(qden))*uback;