Berry
Berry

Reputation: 47

use function code to produce a n×n matrix

enter image description here In order to produce the matrix in the picture, I tried to write a function code to do this, but I cannot figure it out what to do next, and also not sure if what I already did is right or not.

Matrix <- function(n){
  mat1 <- diag(x = ((1:n)-1)/((1:n)+1), n, n)[-1,]
  mat2 <- diag(x = ((1:n)-(1:n)+1)/((1:n)+1), n, n)[,-1]
  mat3 <- diag(x = 1/((1:n)+1), n, n)
}

Upvotes: 1

Views: 44

Answers (2)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84639

An option:

library(SoDA)

n <- 4
triDiag(diagonal = rep(1/(n+1), n+1), 
        upper = (n:1)/(n+1), 
        lower = (1:n)/(n+1))
#       [,1] [,2] [,3] [,4] [,5]
# [1,]  0.2  0.8  0.0  0.0  0.0
# [2,]  0.2  0.2  0.6  0.0  0.0
# [3,]  0.0  0.4  0.2  0.4  0.0
# [4,]  0.0  0.0  0.6  0.2  0.2
# [5,]  0.0  0.0  0.0  0.8  0.2

Upvotes: 1

Oliver
Oliver

Reputation: 8582

It is not entirely clear what you are trying to achieve.

From your description the matrix will have n+1 elements (from 1/(n+1) to n/(n+1)), and I assume the remaining matrix is Sparse. It is not a simple structure to achieve via vectorized computations, but it can be achieved in a single for loop, thus being constructed in O(n) time, given a matrix of size n+1. In the code below i present an example of such code. The idea is to traverse the matrix in opposite, and only assign 1 type value to each.

Create_Matrix <- function(n){
  n1 = n + 1 #Last row, avoid n computations 
  n2 = n1 + 1 
  output <- diag(1/n1, nrow = n1, ncol = n1)
  for(i in seq(n)){
    output[i + 1, i] = output[n1 - i, n2 - i] = output[[1]] * i
  }
  output
}

Upvotes: 0

Related Questions