RIs there a faster way of creating a matrix like the below one that I have created, not only for n =4 but for n=10000.
Each row i
increases i/i 1
m=matrix(c(0),n,n);m
m[1,1]=m[1,2]=1/2
m[2,1]=m[2,2]=m[2,3]=1/3
m[3,1]=m[3,2]=m[3,3]=m[3,4]=1/4
m
I tried the lower.tri()
function but doesn't keep the upper off-diagonal line
n=5
m=matrix(c(1/2,1/3,1/4,1/5,1/6),n,n);m
lower.tri(m,diag=FALSE)
m[upper.tri(m,diag=FALSE)]=0
m
MASS::fractions(m)
CodePudding user response:
The following works:
m = matrix(1 / (seq(n) 1), n, n)
m[row(m) 1L < col(m)] = 0
For n = 4
, the result is:
[,1] [,2] [,3] [,4]
[1,] 0.5000000 0.5000000 0.0000000 0.00
[2,] 0.3333333 0.3333333 0.3333333 0.00
[3,] 0.2500000 0.2500000 0.2500000 0.25
[4,] 0.2000000 0.2000000 0.2000000 0.20
… I’m not sure from your description whether you intended the last row to be all 0s or all 1 / (n 1) but filling it with 0s is trivial.
CodePudding user response:
We may need to add with the transpose
m t(m)