From 400f150a0339f5d228d52da140d8a94e33c1eb19 Mon Sep 17 00:00:00 2001 From: skimport Date: Thu, 24 Jan 2019 15:43:44 -0800 Subject: [PATCH] Week 3 assignment (author update) --- cachematrix.R | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..be4b0fa2ee3 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,33 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## The idea is to create a cache of the inverse of a matrix so as to not have +## to compute it over and over when the matrix has not changed. +## Function that creates a "matrix" that contains its own inverse makeCacheMatrix <- function(x = matrix()) { - + inv <- NULL + set <- function(y) { # set the value of the matrix + x <<- y + inv <<- NULL + } + get <- function() x # get the value of the matrix + setinverse <- function(inverse) inv <<- inverse # set the inverse + getinverse <- function() inv # get the inv + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } -## Write a short comment describing this function - +## Inverts the given matrix, returning the cached inverse if it exists cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + inv <- x$getinverse() + if(!is.null(inv)) { + message("getting cached data") + return(inv) + } + data <- x$get() + inv <- solve(data, ...) + x$setinverse(inv) + inv } + +