Skip to content

Commit 8540eff

Browse files
committed
added logic to either solve or retrieve from a cache a previously solved inverted matrix
1 parent 7f657dd commit 8540eff

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

cachematrix.R

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,42 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## This is a set of two functions that will return the inverse of a matrix.
2+
## If the supplied data has been previously cached, then the data will not be recomputed.
3+
## Note that the code assumes that the matrix supplied is always invertible.
34

4-
## Write a short comment describing this function
55

6+
## This function creates a special "matrix" object that can cache its inverse.
67
makeCacheMatrix <- function(x = matrix()) {
7-
8+
m <- NULL
9+
set <- function(y) {
10+
x <<- y
11+
m <<- NULL
12+
}
13+
get <- function() x
14+
setinverse <- function(solve) m <<- solve
15+
getinverse <- function() m
16+
list(set = set,
17+
get = get,
18+
getinverse = getinverse,
19+
setinverse = setinverse)
820
}
921

1022

11-
## Write a short comment describing this function
12-
23+
## This function computes the inverse of the special
24+
## "matrix" returned by `makeCacheMatrix` above. If the inverse has
25+
## already been calculated (and the matrix has not changed), then
26+
## `cacheSolve` should retrieve the inverse from the cache.
1327
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
28+
# Computing the inverse of a square matrix can be done with the `solve`
29+
# function in R. For example, if `X` is a square invertible matrix, then
30+
# `solve(X)` returns its inverse.
31+
32+
m <- x$getinverse()
33+
if(!is.null(m)) {
34+
message("getting cached data")
35+
return(m)
36+
}
37+
data <- x$get()
38+
m <- solve(data)
39+
x$setinverse(m)
40+
m
1541
}
42+

0 commit comments

Comments
 (0)