Skip to content

Commit 1a52d75

Browse files
committed
Assignment solution for peer review
1 parent 7f657dd commit 1a52d75

File tree

1 file changed

+35
-6
lines changed

1 file changed

+35
-6
lines changed

cachematrix.R

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,44 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## makeCacheMatrix function creates a matrix wrapper that combines matrix data
2+
## with its inverse
3+
## cacheSolve computes the inverse of a matrix created with makeCacheMatrix,
4+
## if it is called more than once with the same object, the cached value of
5+
## matrix inverse is returned
6+
##
7+
## Example
8+
## cm <- makeCacheMatrix(matrix(c(1, 0, -4, -2, 2, 5, 1, -8, 9), 3, 3))
9+
## cacheSolve(cm)
10+
## second call will return a cached value
11+
## cacheSolve(cm)
312

4-
## Write a short comment describing this function
13+
## returns a matrix wrapper object allowing to cache its inverse
514

615
makeCacheMatrix <- function(x = matrix()) {
7-
16+
xinv <- NULL
17+
getinv <- function() xinv
18+
setinv <- function(inverse) xinv <<- inverse
19+
get <- function() x
20+
set <- function(y) {
21+
x <<- y
22+
xinv <<- NULL
23+
}
24+
list(get = get, set = set,
25+
get.inverse = getinv, set.inverse = setinv)
826
}
927

1028

11-
## Write a short comment describing this function
29+
## Cached version of solve for cache matrix objects,
30+
## it returns the inverse of x if solve function succeeds
1231

1332
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
33+
## Return a matrix that is the inverse of 'x'
34+
xinv <- x$get.inverse()
35+
if (is.null(xinv)) {
36+
tryCatch({
37+
xinv <- solve(x$get(), ...)
38+
x$set.inverse(xinv)
39+
}, error = function(e) stop("Non inversible matrix"))
40+
} else {
41+
message("Getting cached matrix inverse")
42+
}
43+
xinv
1544
}

0 commit comments

Comments
 (0)