This is my answer for Assignment in R programing course by John Hopkins University.

Description

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.

makeCacheMatrix

This function creates a special “matrix” object that can cache its inverse. It is a list containing a function to:

  1. set the value of the matrix

  2. get the value of the matrix

  3. set the value of the inverse

  4. 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)
}

CacheSolve

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
}