模型预测控制(MPC)的Matlab代码

这段代码使用二次规划来解决MPC优化问题在每个时间步,并将系统的状态存储在x_history中用于绘图。所得到的图显示了系统状态随时间的演变,服从于MPC问题中指定的约束和目标。

% Define system parameters
A = [0.8, 0.2; 0.6, 0.4];
B = [0.2; 0.1];
C = [0.5, 0.5];
x0 = [0; 0];

% Define MPC parameters
horizon = 10;
Q = eye(2);
R = 0.1;

% Define optimization options
options = optimoptions('quadprog', 'Display', 'off');

% Initialize states and inputs
x = x0;
u = zeros(horizon, 1);

% Loop for a number of steps
for i = 1:100
    % Formulate and solve optimization problem
    H = 2 * blkdiag(Q, R);
    f = zeros(2 * horizon, 1);
    Aeq = [];
    beq = [];
    lb = [];
    ub = [];
    for j = 1:horizon
        if j == 1
            Aeq = [Aeq; C * x];
            beq = [beq; x0];
        else
            Aeq = [Aeq; C * A^(j-1)];
            beq = [beq; 0];
        end
        Aeq = [Aeq, zeros(size(Aeq, 1), horizon - j)];
        lb = [lb; -inf];
        ub = [ub; inf];
    end
    Aineq = [zeros(horizon, horizon), -eye(horizon)];
    bineq = zeros(horizon, 1);
    [z, fval, exitflag] = quadprog(H, f, Aineq, bineq, Aeq, beq, lb, ub, [], options);
    if exitflag ~= 1
        disp('Optimization failed');
        break;
    end
    u(1) = z(1);
    x = A * x + B * u(1);
    
    % Shift inputs for next iteration
    u = [u(2:end); 0];
    
    % Store states for plotting
    x_history(:, i) = x;
end

% Plot results
figure
hold on
plot(x_history(1, :), x_history(2, :), 'b');
xlabel('x1');
ylabel('x2');
title('Model Predictive Control');

你可能感兴趣的:(Matlab,Code,matlab,算法)