Skip to content

Commit 19a9054

Browse files
author
Bruno Marques
committed
Function bodies
1 parent 7f657dd commit 19a9054

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

cachematrix.R

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,33 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Functions for creating an object that stores a matrix and its inverse, when calculated.
2+
## When the matrix is changed, the inverse cache is nullified.
33

4-
## Write a short comment describing this function
4+
## Creates a wrapping object around a matrix that can store a cache of its inverse
55

66
makeCacheMatrix <- function(x = matrix()) {
7-
7+
inv <- NULL # contains the cached inverse
8+
set <- function(y) { # sets a new value and nullifies the inverse cache
9+
x <<- y
10+
inv <<- NULL
11+
}
12+
get <- function() x # retrieves the matrix
13+
setinverse <- function(inverse) inv <<- inverse # sets the inverse cache
14+
getinverse <- function() inv # retrieves the cached inverse
15+
list(set=set, get=get, setinverse=setinverse, getinverse=getinverse)
816
}
917

1018

11-
## Write a short comment describing this function
19+
## Tries to retrieve the inverse matrix of an object created by makeCacheMatrix,
20+
## and calculates it if necessary
1221

1322
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
23+
inv <- x$getinverse()
24+
if(!is.null(inv)) {
25+
# the inverse is already known; no need to recalculate
26+
message("getting cached data")
27+
return(inv)
28+
}
29+
data <- x$get()
30+
inv <- solve(data, ...) # calculates the inverse matrix
31+
x$setinverse(inv) # caches the inverse matrix for future use
32+
inv
1533
}

0 commit comments

Comments
 (0)