Skip to content

Commit 52e3d89

Browse files
committed
Add makeCacheMatrix and cacheSolve functions
1 parent 7f657dd commit 52e3d89

File tree

1 file changed

+35
-7
lines changed

1 file changed

+35
-7
lines changed

cachematrix.R

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,43 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
31

4-
## Write a short comment describing this function
2+
## These functions allow for the caching of "expensive" computations like
3+
## the matrix inverse.
54

6-
makeCacheMatrix <- function(x = matrix()) {
75

6+
## makeCacheMatrix takes a regular matrix and turns it into a "super matrix"
7+
## that stores a matrix and it's inverse result together.
8+
## The matrix is stored as x
9+
## The matrix inverse is stored as inv, set to NULL until the operation is made
10+
## There are 4 accessor functions to get and set the values.
11+
12+
makeCacheMatrix <- function(x = matrix()) {
13+
inv <- NULL
14+
set <- function(y) {
15+
x <<- y
16+
inv <<- NULL
17+
}
18+
get <- function() x
19+
setinverse <- function(inver) inv <<- inver
20+
getinverse <- function() inv
21+
list(set = set, get = get,
22+
setinverse = setinverse,
23+
getinverse = getinverse)
824
}
925

1026

11-
## Write a short comment describing this function
27+
## Returns inverse of matrix "x" from solve()
28+
## This function is very similar to cachemean example
1229

1330
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
31+
## Return a matrix that is the inverse of 'x'
32+
inv <- x$getinverse()
33+
if(!is.null(inv)) {
34+
message("getting cached data")
35+
return(inv)
36+
}
37+
38+
# and if *not* cached, compute inverse and save it
39+
data <- x$get()
40+
inv <- solve(data)
41+
x$setinverse(inv)
42+
inv
43+
}

0 commit comments

Comments
 (0)