【问题标题】:How can i create this exact 5x5 matrix using only matrix operations?如何仅使用矩阵运算创建这个精确的 5x5 矩阵?
【发布时间】:2022-01-14 12:31:21
【问题描述】:

我得到了这个矩阵,我必须使用专门的矩阵运算来创建它。

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

这就是我所做的,但我不确定这是否真的被视为矩阵运算以创建我的 MATNew

mat1 <- matrix(c(0:4), nrow=1, ncol=5) ; print(mat1)
mat2 <- matrix(c(1:5), nrow=1, ncol=5) ; print(mat2)
mat3 <- matrix(c(2:6), nrow=1, ncol=5) ; print(mat3)
mat4 <- matrix(c(3:7), nrow=1, ncol=5) ; print(mat4)
mat5 <- matrix(c(4:8), nrow=1, ncol=5) ; print(mat5)

MATNew <- matrix(cbind(mat1,mat2,mat3,mat4,mat5), 5, 5) ; print(MATNew)

【问题讨论】:

    标签: r matrix


    【解决方案1】:

    踢球基准:

    microbenchmark::microbenchmark(
      outer = outer(0:4, 0:4, `+`),
      rowcol = {m <- matrix(NA, 5, 5); row(m) + col(m)-2},
      matrix1 = matrix(rep(0:8,5), 5)[,1:9%%2==1],
      matrix2 = matrix(rep(0:8,5), 5)[,c(TRUE, FALSE)],
      matrix3 = matrix(rep(0:4, each = 5) + 0:4, 5),
      sequence = matrix(sequence(rep(5, 5), 0:4), 5), times = 1e5)
    #> Unit: microseconds
    #>      expr   min    lq     mean median    uq      max neval
    #>     outer 5.100 6.200 8.706730  6.501 7.202 6628.401 1e+05
    #>    rowcol 2.900 3.801 5.097179  4.002 4.402 4985.501 1e+05
    #>   matrix1 2.900 3.701 5.159770  4.000 4.400 3621.901 1e+05
    #>   matrix2 2.400 3.002 4.063637  3.201 3.601 2395.001 1e+05
    #>   matrix3 2.000 2.600 3.535451  2.701 3.001 2517.101 1e+05
    #>  sequence 3.701 4.601 6.179183  4.901 5.401 3303.102 1e+05
    

    【讨论】:

      【解决方案2】:

      试试这个?

      > embed(0:8, 5)[, 5:1]
           [,1] [,2] [,3] [,4] [,5]
      [1,]    0    1    2    3    4
      [2,]    1    2    3    4    5
      [3,]    2    3    4    5    6
      [4,]    3    4    5    6    7
      [5,]    4    5    6    7    8
      

      【讨论】:

        【解决方案3】:

        matrix-only 解决方案

        matrix( rep(0:8,5), 5 )[,1:9%%2==1]
             [,1] [,2] [,3] [,4] [,5]
        [1,]    0    1    2    3    4
        [2,]    1    2    3    4    5
        [3,]    2    3    4    5    6
        [4,]    3    4    5    6    7
        [5,]    4    5    6    7    8
        

        【讨论】:

          【解决方案4】:

          您可以使用row()col() 函数(如果这是家庭作业,请务必引用您的来源...)

          m <- matrix(NA, 5, 5)
          row(m) + col(m)-2
          

          【讨论】:

            【解决方案5】:
            outer(0:4, 0:4, `+`)
            #      [,1] [,2] [,3] [,4] [,5]
            # [1,]    0    1    2    3    4
            # [2,]    1    2    3    4    5
            # [3,]    2    3    4    5    6
            # [4,]    3    4    5    6    7
            # [5,]    4    5    6    7    8
            

            【讨论】:

              猜你喜欢
              • 2022-01-12
              • 2019-11-09
              • 2020-07-09
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多