Skip to content

Commit ed67861

Browse files
author
John McGrath
committed
Implemented matrix cache functions
1 parent 7f657dd commit ed67861

1 file changed

Lines changed: 49 additions & 8 deletions

File tree

cachematrix.R

Lines changed: 49 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,56 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
1+
## This excercise contains two functions:
2+
## - makeCacheMatrix(x) caches the inverse of a matrix object,
3+
## - cacheSolve, which does the inverting and commits it to the cache.
54

5+
## This function takes a square matrix as a parameter, and returns a special "matrix" object that can cache its inverse.
66
makeCacheMatrix <- function(x = matrix()) {
7-
7+
i <- NULL
8+
9+
# takes a matix, and sets it as the value to calculate the inverse of
10+
set <- function(y) {
11+
x <<- y
12+
i <<- NULL
13+
}
14+
15+
# returns the value to calculate the inverse of
16+
get <- function() x
17+
18+
# caches the inverst of the matrix
19+
setinverse <- function(inverse) i <<- inverse
20+
21+
# gets the cached value of the matrix, or NULL if it hasn't been cached yet
22+
getinverse <- function() i
23+
24+
# return a list with all the function in the object
25+
list(set = set, get = get,
26+
setinverse = setinverse,
27+
getinverse = getinverse)
828
}
929

1030

11-
## Write a short comment describing this function
12-
31+
## This function takes a makeCacheMatrix object.
32+
## The first time it's run, it calculates the inverse of that matrix with `solve`,
33+
## caches it, and returns it. If run again it returns that cached value.
1334
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
35+
36+
# Get the cached inverse from the makeCacheMatrix object
37+
inverse <- x$getinverse()
38+
39+
# If it's not null, return it, along with a message that you've gotten it from the cache
40+
if(!is.null(inverse)) {
41+
message("getting cached data")
42+
return(inverse)
43+
}
44+
45+
# If we've gotten here, it wasn't cached, so get the matrix...
46+
data <- x$get()
47+
48+
# calculate its inverse...
49+
inverse <- solve(data)
50+
51+
# cache it...
52+
x$setinverse(inverse)
53+
54+
# and return it.
55+
inverse
1556
}

0 commit comments

Comments
 (0)