Skip to content

Commit 5388602

Browse files
committed
Update cachematrix.R
programming assignment 2
1 parent 7f657dd commit 5388602

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

cachematrix.R

Lines changed: 28 additions & 7 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
3-
4-
## Write a short comment describing this function
1+
## Creates a special "matrix" object that can cache its inverse.
2+
## x : the matrix to encapsulate
3+
## set(y) : set the matrix
4+
## get : get the matrix
5+
## setinverse(inverse) : set the inverse of the current matrix
6+
## getinverse : retrieve the cached inverse matrix or NULL if no inverse matrix was set
57

68
makeCacheMatrix <- function(x = matrix()) {
7-
9+
inv <- NULL
10+
set <- function(y) {
11+
x <<- y
12+
inv <<- NULL
13+
}
14+
get <- function() x
15+
setinverse <- function(inverse) inv <<- inverse
16+
getinverse <- function() inv
17+
list(set = set, get = get,
18+
setinverse = setinverse,
19+
getinverse = getinverse)
820
}
921

1022

11-
## Write a short comment describing this function
23+
## Compute the inverse matrix of the CacheMatrix x.
24+
## This function returns the cached inverse matrix of x if it exists.
25+
## If not it computes the inverse matrix of the encapsulated matrix of x and caches the result
1226

1327
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
28+
## Return a matrix that is the inverse of 'x'
29+
inv <- x$getinverse()
30+
if (!is.null(inv)) {
31+
return(inv)
32+
}
33+
inv <- solve(x$get())
34+
x$setinverse(inv)
35+
inv
1536
}

0 commit comments

Comments
 (0)