Skip to content

Commit 521a51f

Browse files
committed
Complete cachematrix to compute the cache of the inverse of a matrix
- Implement makeCacheMatrix - Implement cacheSolve
1 parent 7f657dd commit 521a51f

File tree

1 file changed

+37
-8
lines changed

1 file changed

+37
-8
lines changed

cachematrix.R

Lines changed: 37 additions & 8 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+
## cachematrix.R is a set of functions to cache the inverse of a matrix:
2+
##
3+
## Usage:
4+
## m.cached <- makeCacheMatrix(m)
5+
## m.inversed <- cacheSolve(m.cached)
6+
##
7+
## where 'm' is an invertible matrix.
38

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

10+
## makeCacheMatrix creates a special matrix that can be handled by cacheSolve
11+
## It returns a list of 4 functions to
12+
## - set and get a new matrix
13+
## - set and get the inverse of the matrix
614
makeCacheMatrix <- function(x = matrix()) {
7-
15+
m <- NULL
16+
set <- function(y) {
17+
x <<- y
18+
m <<- NULL
19+
}
20+
get <- function() x
21+
setinv <- function(inverse) m <<- inverse
22+
getinv <- function() m
23+
list(set = set, get = get,
24+
setinv = setinv,
25+
getinv = getinv)
826
}
927

1028

11-
## Write a short comment describing this function
12-
29+
## cacheSolve returns the inverse of a matrix created by makeCachedMatrix.
30+
## If the inverse is not stored in the cache, it calculates it and returns it.
31+
## If the inverse is already stored in the cache it returns this value
32+
## skipping the computation.
1333
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
34+
## Return a matrix that is the inverse of 'x'
35+
m <- x$getinv()
36+
if(!is.null(m)) {
37+
message("getting cached data")
38+
return(m)
39+
}
40+
data <- x$get()
41+
m <- solve(data, ...)
42+
x$setinv(m)
43+
m
44+
}

0 commit comments

Comments
 (0)