我需要在R中编写一个函数,该函数接收整数n> 1作为输入,并生成输出矩阵P,其中P_ {i,j} = min(i,j)for(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)
}
}
我知道使用if条件,row(m)和col(m)我应该能够查看矩阵,但是,我不知道如何为该条件设置最小值(i,j)位置的row(m)和col(m)。我知道我无法达到上述条件,但是到目前为止,我距离最近的条件是最接近的。
以下是一个示例。 如果n = 3,则结果应为:
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 2 2
[3,] 1 2 3
答案 0 :(得分:3)
尝试pmin
,row
和col
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
或者使用更有效的outer
和pmin
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