From 60867b731792f3a8f4f9a2f19b09941d4f3acb1d Mon Sep 17 00:00:00 2001 From: Guy Taylor Date: Fri, 10 Apr 2015 15:19:43 +0200 Subject: [PATCH] Generating functions for caching inverted matrices --- cachematrix.R | 48 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 42 insertions(+), 6 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..a231bf6f393 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,51 @@ -## Put comments here that give an overall description of what your -## functions do +## cachematrix.r +## +## makeCacheMatrix: creates special matrix for caching purposes +## +## cacheSolve: returns calculation of cached inversion of a matrix. -## Write a short comment describing this function +## makeCacheMatrix(x) -- +## creates a special matrix, which is really 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 inversion of the matrix +## 4. get the value of the inversion of the matrix makeCacheMatrix <- function(x = matrix()) { - + m <- NULL + + # Set Methods + set <- function(y) { + x <<- y + m <<- NULL + } + get <- function() x + setInverse <- function(solve) <<- solve + getInverse <- function() m + + # Return a list of methods + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } -## Write a short comment describing this function +## cacheSolve(x) -- +## calculates the inversion of a matrix. It first checks to see if a cached version exits (m) +## if so it returns that cached version. Otherwise it calculates the what the inversion should be and creates +## a cached copy. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + m <- x$getInverse() + + # Check if cached version exists + if(!is.null(m)) { + message("getting cached data") + return(m) + } + + # Create and return cached inversion of matrix + matrix <- x$get() + m <- solve(matrix) + x$setInverse(m) + m }