From f5219b8e77d2cf7f1dc65a01b611cd5b2cd4beba Mon Sep 17 00:00:00 2001 From: wal Date: Sat, 26 Apr 2014 23:22:05 +0100 Subject: [PATCH] Assignment 2 --- cachematrix.R | 40 +++++++++++++++++++++++++++++++++------- test.R | 10 ++++++++++ 2 files changed, 43 insertions(+), 7 deletions(-) create mode 100644 test.R diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..9a7200ad994 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,41 @@ -## Put comments here that give an overall description of what your -## functions do +# Create a CacheMatrix, a special Matrix object that can cache its inverse (available by calling getInverse) +makeCacheMatrix <- function(x = matrix()) { -## Write a short comment describing this function + # Initialize inverse as null (will be calculated on demand) + inverse <- NULL + + # A set function to set the Matrix and reset the cached inverse + set <- function(y) { + x <<- y + inverse <<- NULL + } -makeCacheMatrix <- function(x = matrix()) { + # Get function to retrieve the Matrix + get <- function() x -} + # Functions to set and get the cached inverse + setInverse <- function(solve) inverse <<- solve + getInverse <- function() inverse + # Return list of the wrapped functions of the matrix + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) +} -## Write a short comment describing this function +# Check if the inverse has already been calculated for this matrix and return it if so, otherwise calculate and cache the inversex cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + + # check if the inverse has been cached already + inverse <- x$getInverse() + + if(!is.null(inverse)) { + message("Using Cached inverse") + # Use the cached inverse + return(inverse) + } + + # Inverse not cached, calculate and cache it + inverse <- solve(x$get(),...) + x$setInverse(inverse) + inverse } diff --git a/test.R b/test.R new file mode 100644 index 00000000000..6fb4e1c8494 --- /dev/null +++ b/test.R @@ -0,0 +1,10 @@ +source("cachematrix.R") + +a <- makeCacheMatrix(matrix(1:4,2)) +a$get() +a$getInverse() +a$set(matrix(5:8,2)) +a$get() +cacheSolve(a) +cacheSolve(a) +a$getInverse()