This is my answer for Assignment in R programing course by John Hopkins University.
Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix rather than compute it repeatedly (there are also alternatives to matrix inversion that we will not discuss here). My assignment is to write a pair of functions that cache the inverse of a matrix.
This function creates a special “matrix” object that can cache its inverse. It is a list containing a function to:
set the value of the matrix
get the value of the matrix
set the value of the inverse
get the value of the inverse
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, setinverse=setinverse, getinverse=getinverse)
}
The following function calculates the inverse of the special “matrix” created with the above function.
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
}