Berry
Berry

Reputation: 47

how to produce a matrix

How can I produce a matrix in the form below in r? I can produce a matrix with all 0 in there, but I am not sure how to write the for loops to fill in the rest of it.

a <-10
m<-matrix(0,a,a) 

enter image description here

The rest part of the matrix are all 0.

Upvotes: 0

Views: 50

Answers (2)

Tonio Liebrand
Tonio Liebrand

Reputation: 17689

It was a bit harder than expected :), but you could do like this:

createMatrix <- function(n){
  firstCol <- rep(0, n + 2)
  lastCol <- rep(0, n + 2)
  firstCol[c((n + 2), n + 1)] <- c(1 - 1/(n + 2), 1/(n + 1))
  lastCol[c((n + 2), n + 1)] <- c(1/(n + 2), 1 - 1/(n + 1))
  mat1 <- diag(x = 1/(n:1), n, n)[n:1, ]
  mat2 <- diag(x = (1 - 1/(1:n)), n, n)
  mat1[mat1 == 0] <- mat2[mat1 == 0]
  unname(cbind(firstCol, rbind(mat1, rep(0, n), rep(0, n)), lastCol))
}

> createMatrix(4)
          [,1] [,2]      [,3]      [,4] [,5]      [,6]
[1,] 0.0000000 0.00 0.0000000 0.0000000 1.00 0.0000000
[2,] 0.0000000 0.00 0.5000000 0.5000000 0.00 0.0000000
[3,] 0.0000000 0.00 0.3333333 0.6666667 0.00 0.0000000
[4,] 0.0000000 0.25 0.0000000 0.0000000 0.75 0.0000000
[5,] 0.2000000 0.00 0.0000000 0.0000000 0.00 0.8000000
[6,] 0.8333333 0.00 0.0000000 0.0000000 0.00 0.1666667

Upvotes: 1

adjustedR2
adjustedR2

Reputation: 161

For filling one diagonal you can use :

 diag(m) <- "1-1/n"

For the other diagonal you can use a loop(as i cannot figure out the same for other diagonal).

Upvotes: 0

Related Questions