Skip to content

Commit 5c3e431

Browse files
committed
Initial implementation of makeCacheMatrix and cacheSolve functions
1 parent 7f657dd commit 5c3e431

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

cachematrix.R

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,38 @@
11
## Put comments here that give an overall description of what your
22
## functions do
33

4-
## Write a short comment describing this function
4+
## makeCacheMatrix is a function that creates a special "matrix" object
5+
## that can cache its inverse.
56

67
makeCacheMatrix <- function(x = matrix()) {
7-
8+
inverse_x <- NULL
9+
set <- function(y) {
10+
x <<- y
11+
inverse_x <<- NULL
12+
}
13+
get <- function() x
14+
set_inverse <- function(inverse) inverse_x <<- inverse
15+
get_inverse <- function() inverse_x
16+
list(set = set, get = get,
17+
set_inverse = set_inverse,
18+
get_inverse = get_inverse)
819
}
920

1021

11-
## Write a short comment describing this function
22+
## cacheSolve is a function that computes the inverse of the special "matrix"
23+
## returned by makeCacheMatrix above.
24+
## If the inverse has already been calculated (and the matrix has not changed),
25+
## then cacheSolve should retrieve the inverse from the cache.
1226

1327
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
28+
## Return a matrix that is the inverse of 'x'
29+
inverse_x = x$get_inverse()
30+
if (! is.null(inverse_x)) {
31+
message("getting cached data")
32+
return(inverse_x)
33+
}
34+
data <- x$get()
35+
inverse_x <- solve(data, ...)
36+
x$set_inverse(inverse_x)
37+
inverse_x
38+
}

0 commit comments

Comments
 (0)