Skip to content

Commit 1c03031

Browse files
author
simberific
committed
Adding cachematrix.R
1 parent 7f657dd commit 1c03031

File tree

1 file changed

+31
-6
lines changed

1 file changed

+31
-6
lines changed

cachematrix.R

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,40 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Below are two functions, makeCacheMatrix and cacheSolve, which together allow for caching of the inverse of a matrix, so that you don't have to solve for the inverse (which is expensive) if you have already computed this.
32

4-
## Write a short comment describing this function
53

6-
makeCacheMatrix <- function(x = matrix()) {
4+
## makeCacheMatrix creates a matrix object which has functions allowing the user to get the value of the matrix itself, set it, get the "cached" inverse of the matrix, and set the cached inverse of the matrix.
75

6+
makeCacheMatrix <- function(x = matrix()) {
7+
inv <- NULL ## Sets inverse to NULL when you first make the cached entry
8+
9+
## Define a set function which sets the value of the vector and re-sets cached inverse to NULL (since you've changed the vector, the previous inverse is no longer valid)
10+
set <- function(y) {
11+
x <<- y
12+
inv <<- NULL
13+
}
14+
get <- function() x ## get function returns the value of the vector
15+
setinverse <- function(i) inv <<- i ## Sets the cached value of the inverse of x to i
16+
getinverse <- function() inv ## Returns the value of the cached inverse
17+
18+
19+
## Return the four functions as elements of a list
20+
list(set = set, get = get, setinverse = setinverse, getinverse = getinverse)
21+
822
}
923

1024

11-
## Write a short comment describing this function
25+
## cacheSolve checks whether the matrix's inverse has already been computed, and if so, retrieves it; if not, computes it, caches it to the object as inv, and returns it.
1226

1327
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
28+
inv <- x$getinverse()
29+
if (!is.null(inv)) {
30+
## Then you just return the inverse from cache
31+
message("getting cached data")
32+
return(inv)
33+
}
34+
## Else, you compute the inverse
35+
data <- x$get()
36+
newInv <- solve(data, ...)
37+
x$setinverse(newInv) ## Set x's inverse to the newly computed inverse
38+
newInv
39+
1540
}

0 commit comments

Comments
 (0)