Skip to content

Commit a816d9f

Browse files
committed
Implement makeCacheMatrix and cacheSolve
1 parent 7f657dd commit a816d9f

File tree

1 file changed

+33
-11
lines changed

1 file changed

+33
-11
lines changed

cachematrix.R

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,37 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
5-
1+
# makeCacheMatrix creates a special 'matrix' object which can cache its inverse.
62
makeCacheMatrix <- function(x = matrix()) {
7-
3+
m <- NULL
4+
set <- function(y) {
5+
x <<- y
6+
m <<- NULL
7+
}
8+
get <- function() x
9+
setinverse <- function(inverse) m <<- inverse
10+
getinverse <- function() m
11+
list(
12+
set = set,
13+
get = get,
14+
setinverse = setinverse,
15+
getinverse = getinverse
16+
)
817
}
918

10-
11-
## Write a short comment describing this function
12-
13-
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
19+
# cacheSolve computes the inverse of the special 'matrix' returned by
20+
# makeCacheMatrix. If the inverse has already been calculated (and the matrix
21+
# has not changed), then the cachesolve will retrieve the inverse from the cache.
22+
#
23+
# params
24+
# x: a cache matrix created with makeCacheMatrix
25+
cacheSolve <- function(x) {
26+
# see https://class.coursera.org/rprog-004/forum/thread?thread_id=993 for an
27+
# explanation why I don't allow additional parameters `...`.
28+
m <- x$getinverse()
29+
if(!is.null(m)) {
30+
message("getting cached data")
31+
return(m)
32+
}
33+
data <- x$get()
34+
m <- solve(data)
35+
x$setinverse(m)
36+
m
1537
}

0 commit comments

Comments
 (0)