8
8
# these 'special' matrices can be useful in situations where there's the need to
9
9
# repeatedly calculate their inverse.
10
10
11
- makeCacheMatrix <- function (x = matrix ()) {
11
+ makeCacheMatrix <- function (mat = matrix ()) {
12
12
# The cache is always empty in the beginning
13
- m <- NULL
13
+ cache <- NULL
14
14
15
- # Define the matrix proper. Everytime we (re-)define the matrix, the cache is
16
- # cleared to force recalculation of the inverse.
17
- set <- function (y ) {
18
- x <<- y
19
- m <<- NULL
15
+ # Create the matrix
16
+ set <- function (x ) {
17
+ mat <<- x
18
+ cache <<- NULL # (re-)defining the matrix (`mat`) forces computation of inverse
20
19
}
21
20
22
- # Simply return the matrix
23
- get <- function () x
21
+ # Get the matrix
22
+ get <- function () mat
24
23
25
- # Cache the inverse of the matrx in variable `m`.
26
- setinv <- function (inv ) m <<- inv
24
+ # Store the inverted matrix in cache
25
+ setinv <- function (inv ) cache <<- inv
27
26
28
- # Return the contents of the cache (can be an inverted matrix or NULL)
29
- getinv <- function () m
27
+ # Get the cache contents (can be an inverted matrix or NULL)
28
+ getinv <- function () cache
30
29
31
- # Now we return a list with 4 elements (' set', ' get', ' setinv' and ' getinv' ) and
30
+ # Now we return a list with 4 elements (` set`, ` get`, ` setinv` and ` getinv` ) and
32
31
# link them to the appropriate function defined above.
33
32
list (set = set ,
34
33
get = get ,
@@ -41,24 +40,22 @@ makeCacheMatrix <- function(x = matrix()) {
41
40
# If the inverse is already cached (was previously computed), it just returns it.
42
41
# Otherwise, the inverse matrix is computed, saved to the cache and returned.
43
42
#
44
- # Note: we assume matrices passed as argument are invertible.
43
+ # Assumption: every matrix passed as argument is square and invertible
45
44
46
- cacheSolve <- function (x , ... ) {
45
+ cacheSolve <- function (mat , ... ) {
47
46
# Get the contents of the cache
48
- m <- x $ getinv()
47
+ cache <- mat $ getinv()
49
48
50
- if (! is.null(m )) {
51
- # If the cache is not empty (ie. is not NULL)), print a message signaling we're
52
- # returning the cached matrix, return it and exit the function at this point.
49
+ # If the cache isn't empty, return the cached inverted matrix and stop
50
+ if (! is.null(cache )) {
53
51
message(" getting cached data" )
54
- return (m )
52
+ return (cache )
55
53
}
56
54
57
- # If, on the other hand, the cache is empty (m == NULL), run `solve` on the original
58
- # matrix data (obtained via `x$get()`) and store it in the cache (via `x$setinv(n))`).
59
- m <- solve(x $ get(), ... )
60
- x $ setinv(m )
55
+ # If the cache is empty, compute the inverse of the matrix and cache it.
56
+ cache <- solve(mat $ get(), ... )
57
+ mat $ setinv(cache )
61
58
62
59
# Return the computed inverse.
63
- m
60
+ cache
64
61
}
0 commit comments