Skip to content

Commit 244e9ae

Browse files
committed
final implementation of the methods
1 parent 7f657dd commit 244e9ae

File tree

1 file changed

+65
-6
lines changed

1 file changed

+65
-6
lines changed

cachematrix.R

Lines changed: 65 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,74 @@
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+
# the functions below allow us to calculate the inverse of a matrix,
2+
# storing it in cache for faster calculations, assuming that the matrix
3+
# provided is always inversible
54

65
makeCacheMatrix <- function(x = matrix()) {
6+
# this is where we store the cached calculation
7+
cachedMatrix <- NULL
8+
9+
set <- function(y) {
10+
x <<- y
11+
cachedMatrix <<- NULL
12+
}
13+
14+
# returns the original matrix
15+
get <- function() {
16+
return(x)
17+
}
18+
19+
# stores the inverse matrix provided by the function
20+
setSolve <- function(m) {
21+
cachedMatrix <<- m
22+
}
723

24+
# returns the cached inverse matrix
25+
getSolve <- function() {
26+
return(cachedMatrix)
27+
}
28+
29+
list(set = set, get = get, setSolve = setSolve, getSolve = getSolve)
830
}
931

32+
# given a cachedMatrix created with makeCacheMatrix(matrix), this function will
33+
# calculate its inverse matrix
34+
#
35+
# example:
36+
#
37+
# > mat1 <- makeCacheMatrix(matrix(1:4, ncol=2, nrow=2))
38+
#
39+
# > mat1$get()
40+
# [,1] [,2]
41+
# [1,] 1 3
42+
# [2,] 2 4
43+
#
44+
# First call (no cached results):
45+
#
46+
# > cacheSolve(mat1)
47+
# [,1] [,2]
48+
# [1,] -2 1.5
49+
# [2,] 1 -0.5
1050

11-
## Write a short comment describing this function
51+
# Second call (cached results):
52+
#
53+
# > cacheSolve(mat1)
54+
# [1] "getting cached data"
55+
# [,1] [,2]
56+
# [1,] -2 1.5
57+
# [2,] 1 -0.5
1258

1359
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
60+
m <- x$getSolve()
61+
62+
# check whether we got a cached calculation and return it if so
63+
if (!is.null(m)) {
64+
print("getting cached data")
65+
return(m)
66+
} else {
67+
68+
# if we didn't have it in the cache, calculate it and store it
69+
data <- x$get()
70+
m <- solve(data)
71+
x$setSolve(m)
72+
return(m)
73+
}
1574
}

0 commit comments

Comments
 (0)