From a6ca2c430a68601e7993616a86bc8c5ad4a7ec65 Mon Sep 17 00:00:00 2001 From: attarwala Date: Sun, 20 Apr 2014 01:21:24 -0700 Subject: [PATCH] Commit the changes for assignment2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Create special matrix object that is capable of caching it’s inverse once it is computed. --- cachematrix.R | 41 +++++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..dfdc204b80f 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,44 @@ -## Put comments here that give an overall description of what your -## functions do +## The functions here illustrate the use of <<- operator, and lexical scoping +## in general. The idea of lexical scoping is that the function comes together +## with its environment, also referred to as function closure. -## Write a short comment describing this function +## The makeCacheMatrix function creates a special matrix, which has a set of functions +## to set and get the value of the matrix, and to get and set the inverse of that +## matrix. cacheSolve calculates the inverse for this special matrix object, and +## caches the result. Once the result is cached, it returns the cached result till +## the underlying matrix object remains the same. It recomputes and recaches the +## result if the underlying matrix object changes. -makeCacheMatrix <- function(x = matrix()) { +## Create a special matrix object that is capable of caching it's inverse +makeCacheMatrix <- function(x = matrix()) { + matrixInverse <- NULL + set <- function(y) { + x <<- y + matrixInverse <<- NULL + } + get <- function() x + setinverse <- function(inverse) matrixInverse <<- inverse + getinverse <- function() matrixInverse + list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } -## Write a short comment describing this function +## Return the cached inverse for the special matrix object, if the matrix +## has not changed, and the inverse for that already exists, compute otherwise and +## update the cache. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + ## For this assignment we can assume that matrix 'x' is always + ## invertible, so no need to put any checks for that + inv <- x$getinverse() + if (!is.null(inv)) { + message("getting cached data") + return(inv) + } + data <- x$get() + inv <- solve(data, ...) + x$setinverse(inv) + inv }