function [yopt, xopt] = mpc_computeSequence(isLTV, x, uopt, v, mvoff, yoff, xoff, p, ny, nxQP, nv, A, Bu, Bv, C, Dv)
% yopt  Optimal output sequence, dimensionless but including offset
% xopt  Optimal state sequence, dimensionless but including offset
% uopt  Optimal control sequence, dimensionless but including offset

% Authors:  A. Bemporad, N.L. Ricker, R. Chen
% Copyright 1994-2020 The MathWorks, Inc.

%#codegen

% Transform uopt to dimensionless, offset-free form
pmax1 = size(uopt,1);
xQP = x(1:nxQP);
uopt_dim = uopt(1:p,:) - repmat(mvoff,1,p)';
yopt = zeros(pmax1,ny);
xopt = zeros(pmax1,nxQP);
vk = zeros(nv,1);
for k=0:p
    xopt(k+1,:) = xQP';
    % must use loop here to support fixed size data
    for j=1:nv
        vk(j) = v(k*nv+j);
    end
    if isLTV
        A_k = A(1:nxQP,1:nxQP,k+1);
        Bu_k = Bu(1:nxQP,:,k+1);
        Bv_k = Bv(1:nxQP,:,k+1);
        C_k = C(:,1:nxQP,k+1);
        Dv_k = Dv(:,:,k+1);
    else        
        A_k = A(1:nxQP,1:nxQP,1);
        Bu_k = Bu(1:nxQP,:,1);
        Bv_k = Bv(1:nxQP,:,1);
        C_k = C(:,1:nxQP,1);
        Dv_k = Dv(:,:,1);
    end
    yopt(k+1,:) = (C_k*xQP+Dv_k*vk)';
    if k<p
        xQP = A_k*xQP+Bu_k*uopt_dim(k+1,:)'+Bv_k*vk;
    end
end
yopt = yopt + repmat(yoff,1,pmax1)';
xopt = xopt + repmat(xoff(1:nxQP),1,pmax1)';
