我正在尝试了解CVXR包是如何工作的,并且我在这里移植了Steve戴蒙德的一个Python示例:https://groups.google.com/forum/#!topic/cvxpy/5hBSB9KVbuI和http://nbviewer.jupyter.org/github/cvxgrp/cvx_short_course/blob/master/intro/control.ipynb。
代码的R等效项如下:
set.seed(1)
n = 8
m = 2
T1 = 50
alpha = 0.2
beta = 5
A = diag(n) + alpha*replicate(n, rnorm(n))
B = replicate(m, rnorm(n))
x_0 = beta*replicate(1, rnorm(n))
# Form and solve control problem.
x = Variable(n, T1+1)
u = Variable(m, T1)
states = c()
for (t in 1:T1) {
cost = sum_squares(x[,t+1]) + sum_squares(u[,t])
constr = list(x[, t+1] == A%*%x[, t] + B%*%u[, t],
norm_inf(u[,t]) <= 1)
states = c(states, Problem(Minimize(cost), constr) )
}
# sums problem objectives and concatenates constraints.
prob <- Reduce("+", states)
constraints(prob) <- c(constraints(prob), x[ ,T1] == 0)
constraints(prob) <- c(constraints(prob), x[ ,0] == x_0)
sol <- solve(prob)我对倒数第二行有一个挑战(它抛出一个错误):
constraints(prob) <- c(constraints(prob), x[ ,0] == x_0)
我的猜测是x[ , 0]指向变量x的第0个索引位置,这个位置在R中不存在,但是从程序转换的Python中,从for循环中存在第0个索引位置(对于范围(T)中的t)。range(T)是一个从0到49的向量。但在R中,for循环(for (t in 1:T1) )是针对1- 50的向量的。
请多多指教,我们将不胜感激。
谢谢。
发布于 2018-01-17 05:09:47
您需要将索引号增加1,因此x[,1] == x_0和x[,T1+1] == 0分别位于倒数第二行和倒数第三行。否则,您永远不会设置T1+1条目。
https://stackoverflow.com/questions/48257760
复制相似问题