Skip to content

Commit f91158d

Browse files
committed
Complete the makeCacheMatrix and cacheSolve methods
1 parent 7f657dd commit f91158d

File tree

1 file changed

+28
-8
lines changed

1 file changed

+28
-8
lines changed

cachematrix.R

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,35 @@
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+
## Computes and caches the inverse of a square matrix.
2+
##
3+
## Two methods are exposed:
4+
## makeCacheMatrix creates or wraps a matrix to cache its inverse
5+
## cacheSolve returns the cached inverse if available, or computes and caches it otherwise.
56

7+
## Creates or wraps a matrix to cache its inverse
68
makeCacheMatrix <- function(x = matrix()) {
7-
9+
i <- NULL
10+
set <- function(y) {
11+
x <<- y
12+
i <<- NULL
13+
}
14+
get <- function() x
15+
setinverse <- function(inverse) i <<- inverse
16+
getinverse <- function() i
17+
list(set = set, get = get,
18+
setinverse = setinverse,
19+
getinverse = getinverse)
820
}
921

1022

11-
## Write a short comment describing this function
12-
23+
## Returns the cached inverse if available, or computes and caches it otherwise.
1324
cacheSolve <- function(x, ...) {
1425
## Return a matrix that is the inverse of 'x'
15-
}
26+
inverse <- x$getinverse()
27+
if(!is.null(inverse)) {
28+
message("getting cached data")
29+
return(inverse)
30+
}
31+
data <- x$get()
32+
inverse <- solve(data, ...)
33+
x$setinverse(inverse)
34+
inverse
35+
}

0 commit comments

Comments
 (0)