Skip to content

Commit eacd0e4

Browse files
committed
update cachematrix script
1 parent 7f657dd commit eacd0e4

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

cachematrix.R

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,36 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
31

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

6-
makeCacheMatrix <- function(x = matrix()) {
3+
## It creates the special "matrix" and provides accesses
4+
## to retreive and set both the original matrix and its inverse.
5+
76

7+
makeCacheMatrix <- function(x = matrix()) {
8+
inverse <- NULL
9+
set <- function(y) { # set a new matrix
10+
x <<- y
11+
inverse <<- NULL # When the matrix is set, the (cached) inverse is set to NULL
12+
}
13+
get <- function() x # get matrix
14+
setInverse <- function(inv) inverse <<- inv ##Inverse function
15+
getInverse <- function() inverse
16+
list(set = set,
17+
get = get,
18+
setInverse = setInverse,
19+
getInverse = getInverse)
820
}
921

22+
## It calculates the inverse of the matrix provided by makeCacheMatrix
1023

11-
## Write a short comment describing this function
1224

1325
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
26+
## Return a matrix that is the inverse of 'x'
27+
inv <- x$setInverse() # get the cached inverse
28+
if(!is.null(inv)) { # checks if the CacheMatrix has a cached inverse
29+
message("getting cached inverse")
30+
return(inv) # return the cached inverse and exit the function
31+
}
32+
mat <- x$get() # retrive the original matrix
33+
mat.inv <- solve(mat, ...) # invert the original matrix
34+
x$setInverse(mat.inv) # put the inverse matrix calculated in the cache
35+
mat.inv # return the inverse of the input matrix
1536
}

0 commit comments

Comments
 (0)