From 6f39b693d451bda7a0d0d9f1b6f17242f350aa91 Mon Sep 17 00:00:00 2001 From: David Meisner Date: Mon, 14 Apr 2014 17:37:30 -0400 Subject: [PATCH] first commit --- cachematrix.R | 42 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..c6872e15d97 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,45 @@ -## Put comments here that give an overall description of what your -## functions do +## Matrix inversion can be a costly computation. We have therefore created a pair of functions +## which enable caching of the matrix inversion, such that it may be retrieved without repeated +## computations. +## Note: These functions assume that the provided matrix is square and invertible. -## Write a short comment describing this function -makeCacheMatrix <- function(x = matrix()) { +## This function creates a special "matrix" object that can cache its inverse. +## It is actually a list which can: +## 1) Set the value of the matrix +## 2) Get the value of the matrix +## 3) Set the value of the matrix inverse +## 4) Get the value of the matrix inverse +makeCacheMatrix <- function(x = matrix()) { + inv <- NULL + set <- function(y) { + x <<- y + inv <<- NULL + } + get <- function() x + setInv <- function(solve) inv <<- solve + getInv <- function() inv + list(set = set, get = get, + setInv = setInv, + getInv = getInv) } -## Write a short comment describing this function +## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. +## If the inverse has already been calculated (and the matrix has not changed), it gets +## the inverse from the cache and skips the computation. Otherwise, it computes the inverse and sets +## the value of the inverse in the cache. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + inv <- x$getInv() + if(!is.null(inv)) { + message("getting cached data") + return(inv) + } + mat <- x$get() + inv <- solve(mat) + x$setInv(inv) + inv }