R编程:缓存逆矩阵

时间:2017-11-08 02:24:14

标签: r caching

我试图缓存矩阵的逆矩阵:

makeCacheMatrix <- function(x = matrix()) {
    m <- NULL
    set <- function(y) {
        x <<- y
        m <<- NULL
    }
    get <- function() x
    setinverse <- function(inverse) m <<- inverse
    getinverse <- function() m

    list(set = set, get = get, setinvervse = setinverse, getinverse = getinverse)
}


cacheSolve <- function(x, ...) {
    m <- x$getinverse()
    if (! is.null(m)) {
        message("getting cached data")
        return(m)
    }
    data <- x$get()
    m <- solve(data, ...)
    x$setinverse(m)
    m
}

但是出现了以下错误:

**Error in x$setinverse(m) : attempt to apply non-function**

如何解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:1)

以下代码适用于我

rm(list = ls())

makeCacheMatrix <- function(ma = matrix()) {
  im <- NULL
  setMatrix <- function(y) {
    ma <<- y
    im <<- NULL
  }
  getMatrix <- function() ma
  setinverse <- function(inv) im <<- inv
  getinverse <- function() im
  list(setMatrix = setMatrix,
       getMatrix = getMatrix,
       setinverse = setinverse,
       getinverse = getinverse)
}

cacheSolve <- function(x, ...) {
  im <- x$getinverse()
  if (!is.null(im)) {
    message("getting cached inverse matrix")
    return(im)
  }
  data <- x$getMatrix()
  i <- solve(data, ...)
  x$setinverse(i)
  i
}

##testing the functions
B <- matrix(c(1,2,3,4),2,2)

B1 <- makeCacheMatrix(B)
cacheSolve(B1) #inverse returned after computation, no message 

cacheSolve(B1) #inverse returned from cache and message is printed here

B2 <- makeCacheMatrix(-B)
cacheSolve(B1)
cacheSolve(B2)