我的for
循环矩阵有一个变量m
有问题。如何用for循环解决这个矩阵?
[1 1/2 ... 1/(m+1),
1/2 1/3 ... 1/(m+2),
... ... ...,
1/(m+1) 1/(m+2) ... 1/(2m+1)]
我在Matlab上用代码生成它:
m = 10;
m1 = repmat(1:m+1,1,m+1);
m2 = reshape(m1,m+1,m+1);
m3 = m2 + m2' - 1;
m4 = 1./m3;
如何在R中生成相同的代码?
答案 0 :(得分:5)
你可以这样做:
m <- 4
a <- matrix(,m+1, m+1)
a <- 1/(col(a)+row(a)-1)
# > a
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1.0000000 0.5000000 0.3333333 0.2500000 0.2000000
# [2,] 0.5000000 0.3333333 0.2500000 0.2000000 0.1666667
# [3,] 0.3333333 0.2500000 0.2000000 0.1666667 0.1428571
# [4,] 0.2500000 0.2000000 0.1666667 0.1428571 0.1250000
# [5,] 0.2000000 0.1666667 0.1428571 0.1250000 0.1111111
答案 1 :(得分:2)
你也可以这样做:
1/(matrix(seq_len(m),m,m,byrow=TRUE) + rep(seq_len(m),times=m)-1)
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1.0000000 0.5000000 0.3333333 0.2500000 0.2000000
# [2,] 0.5000000 0.3333333 0.2500000 0.2000000 0.1666667
# [3,] 0.3333333 0.2500000 0.2000000 0.1666667 0.1428571
# [4,] 0.2500000 0.2000000 0.1666667 0.1428571 0.1250000
# [5,] 0.2000000 0.1666667 0.1428571 0.1250000 0.1111111
<强>基准强>
library(microbenchmark)
f_jogo1=function(m) {a <- matrix(,m, m);1/(col(a)+row(a)-1)}
f_jogo2=function(m) 1/(outer(1:(m), 1:(m), '+')-1)
f_989=function(m) 1/(matrix(seq_len(m),m,m,byrow=TRUE) + rep(seq_len(m),times=m)-1)
m <- 1000
all(f_jogo1(m)==f_989(m))
# [1] TRUE
all(f_jogo2(m)==f_989(m))
# [1] TRUE
res <- microbenchmark(f_jogo1(m), f_jogo2(m), f_989(m))
print(res, order="mean")
# Unit: milliseconds
# expr min lq mean median uq max neval
# f_989(m) 8.118373 9.590521 19.40905 10.43484 40.12283 42.63866 100
# f_jogo2(m) 8.946466 9.783122 22.37673 10.70451 40.57098 42.50735 100
# f_jogo1(m) 10.151347 11.758405 27.85950 41.25485 42.30168 44.51509 100