Skip to content

Commit 6c3d853

Browse files
author
Ludovic Claude
committed
Wrote the cache matrix functions
1 parent 7f657dd commit 6c3d853

File tree

1 file changed

+39
-6
lines changed

1 file changed

+39
-6
lines changed

cachematrix.R

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,48 @@
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+
## Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of
2+
## a matrix rather than compute it repeatedly.
3+
## makeCacheMatrix and cacheSolve can be used to create a matrix that is able to cache its inverse.
4+
## Typical usage:
5+
## ````
6+
## m <- makeCacheMatrix(matrix(1:4,2,2))
7+
## cacheSolve(m)
8+
## m$get()
9+
## cacheSolve(m)
10+
## ````
511

12+
## makeCacheMatrix creates a special "matrix", which is really a list containing a function to
13+
## 1. set the value of the matrix
14+
## 2. get the value of the matrix
15+
## 3. set the value of the inverse matrix
16+
## 4. get the value of the inverse metrix
617
makeCacheMatrix <- function(x = matrix()) {
18+
19+
i <- NULL
20+
set <- function(y) {
21+
x <<- y
22+
i <<- NULL
23+
}
24+
get <- function() x
25+
setinverse <- function(inverse) i <<- inverse
26+
getinverse <- function() i
27+
list(set = set, get = get,
28+
setinverse = setinverse,
29+
getinverse = getinverse)
730

831
}
932

1033

11-
## Write a short comment describing this function
34+
## cacheSolve takes a cached matrix as argument and returns the inverse of the matrix.
35+
## The inverse is stored inside the cached matrix on first call, then retrived from the cache on subsequent calls.
1236

1337
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
38+
## Return a matrix that is the inverse of 'x'
39+
i <- x$getinverse()
40+
if(!is.null(i)) {
41+
message("getting cached data")
42+
return(i)
43+
}
44+
data <- x$get()
45+
i <- solve(data, ...)
46+
x$setinverse(i)
47+
i
1548
}

0 commit comments

Comments
 (0)