我收到此错误:
Error in x$getinverse : $ operator is invalid for atomic vectors
我的代码是这样的。我不明白我在哪里弄错了。
##create a function which starts with a null matrix argument
makeCacheMatrix <- function(x = matrix()) {
## initialize the value of the matrix inverse to NULL
matrixinverse <- NULL
## delcare another function set where the value will be cached in 1. Matrix is created
## for the first time. 2. changes made to cached matrix
set <- function(y) {
x <<- y
## change the value of inverse of the matrix in case the matrix was changed.
matrixinverse <<- NULL
}
## gets the value of the inverse
get <- function() x
#calculates the inverse of non-singular matrix via the solve function
setinverse <- function(solve) matrixinverse <<- solve
# gets the inverse
getinverse <- function() matrixinverse
## passes the value of the function makeCacheMatrix
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
# used to get the cache of the matrix
cacheSolve<- function(x, ...) {
matrixinverse <- x$getinverse()
#if the inverse exists, it gets it.
if(!is.null(matrixinverse)) {
message("getting cached data - Inverse of the matrix")
return(matrixinverse)
}
#if the inverse if not there, first it is calculated and then retrieved.
data <- x$get()
matrixinverse <- solve(data, ...)
x$setinverse(matrixinverse)
matrixinverse
}
答案 0 :(得分:5)
You probably are passing the matrix itself to the cacheSolve function , rather than passing the return object of the makeCacheMatrix.
I was facing the same problem earlier. I corrected the input parameter for cacheSolve and it worked.
Here is the illustration :
> mat<-matrix(c(1,4,9,0,-3,2,2,7,8),3,3)
> mat
[,1] [,2] [,3]
[1,] 1 0 2
[2,] 4 -3 7
[3,] 9 2 8
m1<-makeCacheMatrix(mat)
> cacheSolve(mat)
Error in x$getinverse : $ operator is invalid for atomic vectors
But if you correct the input and re-run :
> cacheSolve(m1)
[,1] [,2] [,3]
[1,] -1.18750 0.1250 0.18750
[2,] 0.96875 -0.3125 0.03125
[3,] 1.09375 -0.0625 -0.09375
Hope that helps !
答案 1 :(得分:-1)
我发现更改函数以指定y也是一个矩阵解决了问题。希望这有帮助!
set <- function(y = matrix()) {
x <<- y*
...
}