我需要在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)我应该能够查看矩阵,但是,我不知道如何设置那个条件我可以有行的最小值(m )和(i,j)位置的col(m)。我知道我不会用上面的条件来实现后者,但到目前为止我是最接近的。
一个例子如下。如果n = 3,则结果应为:
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 2 2
[3,] 1 2 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
或者使用更有效的qazxsw poi和qazxsw poi
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)