From 9e51237c28bb64af204fb786e0c6a8a686d91c4f Mon Sep 17 00:00:00 2001 From: Jonathan Bona Date: Sat, 23 May 2015 11:07:52 -0400 Subject: [PATCH] Completed assignment --- cachematrix.R | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..3c2bdefb6a1 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,42 @@ -## Put comments here that give an overall description of what your -## functions do +## These functions take advantage of R's scoping rules to "cache" potentiall expensive +## matrix inverse operations -## Write a short comment describing this function -makeCacheMatrix <- function(x = matrix()) { +## makeCacheMatrix creates a special "matrix", which is a list of functions to: +## set the value of the matrix +## get the value of the matrix +## set the value of the matrix's inverse +## get the value of the matrix's inverse +makeCacheMatrix <- function(x = matrix()) { + i <- NULL + + set <- function(y){ + x <<- y + i <<- NULL + } + get <- function() x + setinverse <- function(inverse) i <<- inverse + getinverse <- function() i + # returns a list of these functions + list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } -## Write a short comment describing this function - +## Calculates the inverse of a "matrix" created by makeCacheMatrix +## If the inverse has already been calculated and cached, return it. +## Otherwise: calcaulate, cache, and return it. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + i <- x$getinverse() + # already cached? return it + if(!is.null(i)){ + message("getting cached inverse") + return(i) + } + + data <- x$get() # get the matrix + i <- solve(data) # calculate its inverse + x$setinverse(i) # cache the inverse + i # return it }