From 119c52cf8a99245997c609b6d8a9ef90062aba3a Mon Sep 17 00:00:00 2001 From: Xiaodan Zhang Date: Sun, 20 Apr 2014 00:46:11 -0500 Subject: [PATCH 1/2] First submission of ProgrammingAssignment2 --- cachematrix.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..a9a02941612 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,4 +1,4 @@ -## Put comments here that give an overall description of what your +# Put comments here that give an overall description of what your ## functions do ## Write a short comment describing this function From 3a7408235074ee4ee0322ac3e395e314aef5dc2a Mon Sep 17 00:00:00 2001 From: Xiaodan Zhang Date: Sun, 20 Apr 2014 17:16:45 -0500 Subject: [PATCH 2/2] modified cachematrix function --- cachematrix.R | 58 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 50 insertions(+), 8 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a9a02941612..595f4ec6742 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,57 @@ -# Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +# The first function, makeCacheMatrix creates a special "matrix", +# which is really 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()) { - + # initialize the inverse matrix value + inv <- NULL + + # set the value of the matrix + set <- function(y) { + x <<- y + inv <<- NULL + } + + # get the value of the matrix + get <- function() x + + # set the value of the inverse + set_inverse <- function(inv_input) inv <<- inv_input + # get the value of the inverse + get_inverse <- function() inv + + # return a list of all the above functions + list(set = set, get = get, + set_inverse = set_inverse, + get_inverse = get_inverse) + } - -## Write a short comment describing this function +## The following function calculates the inverse of the special +## "matrix" created with the above function. +## It first checks to see if the inverse has already been calculated. +## If so, it gets the inverse from the cache and skips the +## computation. Otherwise, it calculates the inverse of the +## matrix and sets the value of the inverse in the cache via +## the setinv function. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + # check if the inverse is already cached, + # if so, we get the inverse from the cache directly + inv <- x$get_inverse() + if(!is.null(inv)) { + message("getting cached inverse") + return(inv) + } + # else, we first get the matrix + data <- x$get() + # and calculate the inverse + inv <- solve(data, ...) + # next, cache the inverse of the matrix + x$set_inverse(inv) + # and finally, return the result + inv }