Search code examples
rintegrationnumericalinverse

Inverse of matrix and numerical integration in R


in R I try to 1) get a general form of an inverse of a matrix (I mean a matrix with parameters instead of specific numbers), 2) then use this to compute an integral.

I mean, I've got a P matrix with a parameter theta, I need to add and subtract something, then take an inverse of this and multiply it by a vector so that I am given a vector pil. From the vector pil I take term by term and multiply it by a function with again the parameter theta and the result must be integrated from 0 to infinity.

I tried this, but it didn't work because I know the result should be pst= (0.3021034 0.0645126 0.6333840)

c<-0.1
g<-0.15
    integrand1 <- function(theta) {
  pil1 <- function(theta) {
    P<-matrix(c( 
      1-exp(-theta), 1-exp(-theta),1-exp(-theta),exp(-theta),0,0,0,exp(-theta),exp(-theta)
    ),3,3);
    pil<-(rep(1,3))%*%solve(diag(1,3)-P+matrix(1,3,3));
    return(pil[[1]])
  }
  q<-pil1(theta)*(c^g/gamma(g)*theta^(g-1)*exp(-c*theta))
  return(q)}

(pst1<-integrate(integrand1, lower = 0, upper = Inf)$value)
#0.4144018

This was just for the first term of the vector pst, because when I didn't know how to a for cycle for this.

Please, do you have any idea why it won't work and how to make it work?


Solution

  • Functions used in integrate should be vectorized as stated in the help. At the end of your code add this

    integrand2 <- Vectorize(integrand1)
    integrate(integrand2, lower = 0, upper = Inf)$value
    #[1] 0.3021034
    

    The result is the first element of your expected result.

    You will have to present more information about the input to get your expected vector.