Skip to content

Commit a3aab03

Browse files
author
Jason Rush
committed
Implemented the makeCacheMatrix() and cacheSolve() functions
1 parent 7f657dd commit a3aab03

File tree

1 file changed

+57
-7
lines changed

1 file changed

+57
-7
lines changed

cachematrix.R

Lines changed: 57 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,65 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## The following functions cache the inverse of a matrix, calculating it
2+
## the first time, and using the cached copy after that until the cache
3+
## is invalidated.
4+
## Usage:
5+
##
6+
## x <- matrix(1:4, 2, 2)
7+
## y <- makeCacheMatrix(x)
8+
## cacheSolve(y) # This calculates the inverse and caches it
9+
##
10+
## [,1] [,2]
11+
## [1,] -2 1.5
12+
## [2,] 1 -0.5
13+
##
14+
## cacheSolve(y) # This pulls the inverse from the cache
15+
##
16+
## getting cached data
17+
## [,1] [,2]
18+
## [1,] -2 1.5
19+
## [2,] 1 -0.5
320

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

6-
makeCacheMatrix <- function(x = matrix()) {
22+
## makeCacheMatrix creates a wrapper for a matrix object, providing access
23+
## to a cached copy of the matrix's inverse.
24+
## Arguments:
25+
## => x: a square, invertible matrix
26+
## Returns a list with the following functions:
27+
## => get: returns the original matrix
28+
## => set: sets the matrix
29+
## => getinv: returns the inverse of the matrix.
30+
## => setinv: sets the inverse of the matrix
731

32+
makeCacheMatrix <- function(x = matrix()) {
33+
inv <- NULL
34+
set <- function(y) {
35+
x <<- y
36+
inv <<- NULL
37+
}
38+
get <- function() x
39+
setinv <- function(newInv) inv <<- newInv
40+
getinv <- function() inv
41+
list(set = set, get = get,
42+
setinv = setinv,
43+
getinv = getinv)
844
}
945

10-
11-
## Write a short comment describing this function
46+
## Returns the inverse of a matrix, caching the result of the inverse the
47+
## first time it is calculated, and using the cached result for future calls.
48+
## Arguments:
49+
## => x: a cache-matrix (the result returned from makeCacheMatrix)
50+
## => ... additional arguments to be passed to solve()
51+
## Returns a matrix which is the inverse of the matrix stored in x.
52+
## Gets the returned matrix from cache if possible, and if not, calculates
53+
## it and caches it for future calls.
1254

1355
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
56+
inv <- x$getinv()
57+
if(!is.null(inv)) {
58+
message("getting cached data")
59+
return(inv)
60+
}
61+
data <- x$get()
62+
inv <- solve(data, ...)
63+
x$setinv(inv)
64+
inv
1565
}

0 commit comments

Comments
 (0)