How to generate a matrix with a sequence based on one variable m

I have a problem with a for

single variable loop matrix m

. How do I solve this matrix using a loop?

[1 1/2 ... 1/(m+1), 
1/2 1/3 ... 1/(m+2),
 ... ... ..., 
1/(m+1) 1/(m+2) ... 1/(2m+1)]

      

I am creating it in Matlab with code:

m = 10;
m1 = repmat(1:m+1,1,m+1);
m2 = reshape(m1,m+1,m+1);
m3 = m2 + m2' - 1;
m4 = 1./m3;

      

How can I generate the same code in R?

+3


source to share


2 answers


You can do:



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

      

+5


source


You can also do:

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

      


Benchmarking



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

      

+2


source







All Articles