Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 63708c3

Browse files
committed
Implement the cacheSolve and makeCacheMatrix functions
1 parent 7f657dd commit 63708c3

File tree

1 file changed

+36
-8
lines changed

1 file changed

+36
-8
lines changed

cachematrix.R

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,43 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Expensive calculations can be cached so that subsequent
2+
## requests for the same calculation will be much faster.
33

4-
## Write a short comment describing this function
4+
## makeCacheMatrix is initialized with a matrix and
5+
## provides functions to cache the result of finding
6+
## the inverse of that matrix.
7+
## set: sets the stored matrix x and
8+
## get: returns the stored matrix x
9+
## setInverse: caches the inverse of the matrix x
10+
## getInverse: returns the cached inverse of the matrix x
511

612
makeCacheMatrix <- function(x = matrix()) {
7-
13+
invMatrix = NULL
14+
set = function(newMatrix) {
15+
x <<- newMatrix
16+
invMatrix <<- NULL
17+
}
18+
get = function() x
19+
setInverse = function(newInvMatrix) invMatrix <<- newInvMatrix
20+
getInverse = function() invMatrix
21+
list(
22+
set = set,
23+
get = get,
24+
setInverse = setInverse,
25+
getInverse = getInverse
26+
)
827
}
928

10-
11-
## Write a short comment describing this function
29+
## cacheSolve takes a matrix wrapped in the makeCacheMatrix function.
30+
## If the inverse matrix is not already calculated, it solves it
31+
## and stores it in the makeCacheMatrix object and returns
32+
## the inverse matrix.
33+
## If the inverse matrix is already calculated, it returns the
34+
## inverse matrix
1235

1336
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
37+
invMatrix = x$getInverse()
38+
if(is.null(invMatrix)) {
39+
invMatrix = solve(x$get())
40+
x$setInverse(invMatrix)
41+
}
42+
invMatrix
43+
}

0 commit comments

Comments
 (0)