用for循环创建矩阵

Stata_user

我正在尝试为 n 行和 n+1 列创建以下矩阵 A。n 可能在 20 或 30 左右,但出于这个问题的目的,我将其放在 4 和 5。

在此处输入图片说明

这是我到目前为止所拥有的:

N <- 5             # n+1
n <- 4             # n
columns <- list()

# first column:
columns[1] <- c(-1, 1, rep(0, N-2))

# all other columns:
for(i in N:2) { 
 columns[i] <- c((rep(0, N-i), 1, -2, 1, rep(0, i-3)))
}

# combine into matrix:

A <- cbind(columns)

我不断收到以下错误消息:

In columns[1] <- c(-1, 1, rep(0, N - 2)) :
  number of items to replace is not a multiple of replacement length

然后

"for(i in N:2) { 
  columns[i] <- c((rep(0, N-i),"
 }
Error: unexpected '}' in "}"
托马斯正在编码
  • 我想你可以尝试for下面循环来创建你的矩阵A
N <- 5
n <- 4
A <- matrix(0,n,N)
for (i in 1:nrow(A)) {
  if (i == 1) {
    A[i,1:2] <- c(-1,1)
  } else {
    A[i,i+(-1:1)] <- c(1,-2,1)
  }
}

以至于

> A
     [,1] [,2] [,3] [,4] [,5]
[1,]   -1    1    0    0    0
[2,]    1   -2    1    0    0
[3,]    0    1   -2    1    0
[4,]    0    0    1   -2    1
  • 另一种解决方案是使用outer,这种方法比for循环方法更快,看起来更紧凑,即,
A <- `diag<-`(replace(z<-abs(outer(1:n,1:N,"-")),!z %in% c(0,1),0),
              c(-1,rep(-2,length(diag(z))-1)))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章