具有(i,j)值且无for或while循环的矩阵中的运算

具有(i,j)值且无for或while循环的矩阵中的运算,r,matrix,R,Matrix,我需要在R中写一个函数,它接收一个整数n>1作为输入,并生成一个输出矩阵p,其中p_{I,j}=min(I,j)(I,j)=1,…,n。此函数不能有for或while循环 到目前为止,我已经尝试了以下代码 mat <- function(n){ m <- matrix(0,nrow = n,ncol = n) if(row(m) >= col(m)){ col(m) } else{ row(m) } } 尝试pmin,行和列 f1 <

我需要在R中写一个函数,它接收一个整数n>1作为输入,并生成一个输出矩阵p,其中p_{I,j}=min(I,j)(I,j)=1,…,n。此函数不能有
for
while
循环

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

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

尝试
pmin

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
基准

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

library(ggplot2)
autoplot(b)
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