-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolveLQR.m
More file actions
73 lines (63 loc) · 1.65 KB
/
Copy pathsolveLQR.m
File metadata and controls
73 lines (63 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
% solve LQR problem and return optimal control gain
function [Kopt, S, M, Qbar, Rbar] = solveLQR(N, A, B, Q, R, P)
% Compute the matrices S, M, Qbar, Rbar, and K0N
% for the unconstrained LQ-MPC problem
%
% Inputs:
% N: Prediction horizon
% A: State transition matrix
% B: Input matrix
% Q: State cost matrix
% R: Input cost matrix
% P: Terminal state cost matrix
nx = size(A, 1);
nu = size(B, 2);
% Initialize matrices
S = zeros(N * nx, N * nu);
M = zeros(N * nx, nx);
Qbar = zeros(N * nx, N * nx);
Rbar = zeros(N * nu, N * nu);
% Compute the first column of S
for i = 1:N
rowStart = (i - 1) * nx + 1;
rowEnd = i * nx;
S(rowStart:rowEnd, 1:nu) = A^(i - 1) * B;
end
% Pad the first column and set it to other columns of S
for i = 2:N
colStart = (i - 1) * nu + 1;
colEnd = i * nu;
zeroRows = (i - 1) * nx;
zeroCols = nu;
S(:, colStart:colEnd) = [zeros(zeroRows, zeroCols); S(1:end - zeroRows, 1:nu)];
end
% Compute first row of M
M(1:nx, :) = A;
% Compute the rest of M
for i = 2:N
rowStart = (i - 1) * nx + 1;
rowEnd = i * nx;
% just multiply the previous rows by A to get higher powers
M(rowStart:rowEnd, :) = A * M(rowStart - nx:rowEnd - nx, :);
end
% Compute Qbar except for the last row
for i = 1:N
% Q is square so we can reuse indices
rowStart = (i - 1) * nx + 1;
rowEnd = i * nx;
temp = Q;
if i == N
temp = P;
end
Qbar(rowStart:rowEnd, rowStart:rowEnd) = temp;
end
% Compute Rbar
for i = 1:N
% R is square so we can reuse indices
rowStart = (i - 1) * nu + 1;
rowEnd = i * nu;
Rbar(rowStart:rowEnd, rowStart:rowEnd) = R;
end
% Compute Optimal Control Gain
Kopt = -inv(S' * Qbar * S + Rbar) * S' * Qbar * M;
end