【问题标题】:Operations in a matrix with (i,j) values with no for or while loops具有 (i,j) 值且没有 for 或 while 循环的矩阵中的操作
【发布时间】:2019-04-27 19:21:26
【问题描述】:

我需要在 R 中编写一个函数,它接收一个整数 n>1 作为输入,并生成一个输出矩阵 P,其中 P_{i,j} = min (i,j) for(i,j)= 1,...,n.此函数不得有 forwhile 循环。

到目前为止,我已经尝试过以下代码。

mat <- function(n){
  m <- matrix(0,nrow = n,ncol = n)
  if(row(m) >= col(m)){
    col(m)
  }
  else{
    row(m)
  }
}

我知道在 if 条件下,row(m) 和 col(m) 我应该能够查看矩阵,但是,我不知道如何为该条件设置它,我可以得到最小值row(m) 和 col(m) 在 (i,j) 位置。我知道在上面的条件下我不会达到后者,但到目前为止是我最接近的。

一个例子如下。 如果 n=3,那么结果应该是:

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    2    2
[3,]    1    2    3

【问题讨论】:

    标签: r matrix


    【解决方案1】:

    试试pminrowcol

    f1 <- function(n = 3) {
      mat <- matrix(nrow = n, ncol = n)
      pmin(row(mat), col(mat))
    }
    
    
    f1()
    #     [,1] [,2] [,3]
    #[1,]    1    1    1
    #[2,]    1    2    2
    #[3,]    1    2    3
    

    或者使用outerpmin 更高效

    f2 <- function(n = 3) {
      idx <- sequence(n)
      outer(idx, idx, pmin)
    }
    

    基准测试

    library(microbenchmark)
    n <- 10000
    b <- microbenchmark(
      f1 = f1(n),
      f2 = f2(n),
      times = 10
    )
    
    library(ggplot2)
    autoplot(b)
    

    b
    #Unit: seconds
    # expr      min       lq     mean   median       uq      max neval cld
    #   f1 5.554471 5.908210 5.924173 5.950610 5.996274 6.058502    10   b
    #   f2 1.272793 1.298099 1.354428 1.309208 1.464950 1.495362    10  a 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多