Skip to content

Commit 64a5da8

Browse files
makeCacheMatrix and cacheSolve methods
1 parent 7f657dd commit 64a5da8

File tree

1 file changed

+32
-7
lines changed

1 file changed

+32
-7
lines changed

cachematrix.R

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,40 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## A pair of functions that cache the inverse of a matrix
32

4-
## Write a short comment describing this function
3+
## makeCacheMatrix: This function creates a special "matrix" object that can cache its inverse (solve).
4+
# It creates a special "matrix", which is really a list containing a function to:
5+
# set the value of the matrix
6+
# get the value of the matrix
7+
# set the value of the solve
8+
# get the value of the solve
59

610
makeCacheMatrix <- function(x = matrix()) {
7-
11+
s <- NULL
12+
set <- function(y) {
13+
x <<- y
14+
s <<- NULL
15+
}
16+
get <- function() x
17+
setsolve <- function(solve) s <<- solve
18+
getsolve <- function() s
19+
list(set = set, get = get,
20+
setsolve = setsolve,
21+
getsolve = getsolve)
822
}
923

1024

11-
## Write a short comment describing this function
12-
25+
## cacheSolve: This function computes the inverse of the special "matrix" returned by makeCacheMatrix above.
26+
# If the inverse has already been calculated (and the matrix has not changed),
27+
# then cacheSolve should retrieve the inverse from the cache.
1328
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
29+
# Return a matrix that is the inverse of 'x'
30+
s <- x$getsolve()
31+
if(!is.null(s)) {
32+
message("getting cached solve")
33+
return(s)
34+
}
35+
data <- x$get()
36+
# Computing the inverse of a square matrix can be done with solve(x)
37+
s <- solve(data, ...)
38+
x$setsolve(s)
39+
s
1540
}

0 commit comments

Comments
 (0)