diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..548684a7e47 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,49 @@ -## Put comments here that give an overall description of what your -## functions do +## Programming Assignment 2 - makeCacheMatrix and cacheSolve +## Example usage: +## a <- matrix(c(5,2,6,1,2,3,8,9,1), 3, 3) +## b <- makeCacheMatrix(a) +## cacheSolve(b) -## Write a short comment describing this function +## makeCacheMatrix 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 inverse of the matrix +## 4. Get the value of the inverse of the matrix makeCacheMatrix <- function(x = matrix()) { - + m <- NULL + set <- function(y) { + x <<- y + m <<- NULL + } + get <- function() { + x + } + + setinverse <- function(inverse) { + m <<- inverse + } + + getinverse <- function() { + m + } + + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } - -## Write a short comment describing this function +## cacheSolve calculates the inverse of the matrix created with makeCacheMatrix but first checks to see if a value has already been computed and if so uses that rather than doing the computation again. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' -} + m2 <- x$getinverse() + if(!is.null(m2)) { + return(m2) + } + data <- x$get() + m2 <- solve(data, ...) + x$setinverse(m2) + m2 + +} \ No newline at end of file