用 R 绘制 Hankel 矩阵

Tho*_* Vo 1 r matrix

我想提请只有R中,使用一个汉克尔矩阵matrix()seq()rep()R的功能到现在为止,我以某种方式作出这样的:

#Do this exercise with other packages, need to rework
install.packages("matrixcalc")
library(matrixcalc)
E1 <- hankel.matrix( 5, seq( 1, 9 ) )
print(E1)
#Use matrix() only, not efficient
E2 <- matrix(c(1,2,3,4,5,2,3,4,5,6,3,4,5,6,7,4,5,6,7,8,5,6,7,8,9), ncol=5)
print(E2)
#Use seq() but not worked
E3 <- matrix(c(seq(1:5),seq(2:6),seq(3:7),seq(4:8),seq(5:9)), ncol=5)
print(E3)
Run Code Online (Sandbox Code Playgroud)

E1 使用了一个库来绘制一个 Hankel 矩阵,在 E2 中,我尝试手动输入数字来绘制一个,但是如果我想要一个新的大矩阵会花费很多时间。我尝试使用seq()但它不起作用。它会画成这样:

      [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3
[4,]    4    4    4    4    4
[5,]    5    5    5    5    5
Run Code Online (Sandbox Code Playgroud)

我对 R 还是很陌生,所以欢迎每个想法。

ags*_*udy 5

你可以这样做 :

matrix(rep(1:5,5)+rep(0:4,each=5),ncol=5)
#       [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    3    4    5
# [2,]    2    3    4    5    6
# [3,]    3    4    5    6    7
# [4,]    4    5    6    7    8
# [5,]    5    6    7    8    9
Run Code Online (Sandbox Code Playgroud)

或者更优雅但使用outer

outer(0:4,1:5,'+')
Run Code Online (Sandbox Code Playgroud)

编辑 :

rep解决方案是这样的:

    12345 12345 12345 ...  (rep times,      repeat the vector n times
  + 00000 11111 22222 ...  (rep with each , repeat each element n times
  = 12345 23456 34567 .....
Run Code Online (Sandbox Code Playgroud)

outer一开始可能会很棘手,也许这里的这个答案可以帮助您理解它并进行一般调试。