Reputation: 5405
I am getting this error:
Error in x$getinverse : $ operator is invalid for atomic vectors
My code is this. I can't understand where am I making a mistake.
##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
}
Upvotes: 3
Views: 5839
Reputation: 33
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
Upvotes: 6
Reputation: 1
I found changing the function to specify that y is also a matrix solved the problem. Hope this helps!
set <- function(y = matrix()) {
x <<- y*
...
}
Upvotes: -1