Skip to content
This repository was archived by the owner on Dec 31, 2024. It is now read-only.

Commit c8291c2

Browse files
committed
Implement the functions makeCacheMatrix and cacheSolve
1 parent ca4b7ff commit c8291c2

File tree

1 file changed

+39
-7
lines changed

1 file changed

+39
-7
lines changed

cachematrix.R

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,47 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
# Coursera - R Programming - Programming Assignment 2
2+
# Caching the Inverse of a Matrix
33

4-
## Write a short comment describing this function
4+
# makeCacheMatrix: This function creates a special "matrix" object that can
5+
# cache its inverse
56

67
makeCacheMatrix <- function(x = matrix()) {
7-
8+
m <- NULL
9+
set <- function(y) {
10+
x <<- y
11+
m <<- NULL
12+
}
13+
get <- function() x
14+
setsolve <- function(solve) m <<- solve
15+
getsolve <- function() m
16+
list(set = set, get = get,
17+
setsolve = setsolve,
18+
getsolve = getsolve)
819
}
920

10-
11-
## Write a short comment describing this function
21+
# cacheSolve: This function computes the inverse of the special "matrix"
22+
# returned by makeCacheMatrix above. If the inverse has already been
23+
# calculated (and the matrix has not changed), then the cachesolve should
24+
# retrieve the inverse from the cache.
1225

1326
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
27+
## Return a matrix that is the inverse of 'x'
28+
m <- x$getsolve()
29+
if(!is.null(m)) {
30+
message("getting cached data")
31+
return(m)
32+
}
33+
data <- x$get()
34+
m <- solve(data, ...)
35+
x$setsolve(m)
36+
m
1537
}
38+
39+
# Tested as follows:
40+
# m1 <- matrix(c(1,2,3,4), nrow = 2, ncol = 2)
41+
# m2 <- matrix(c(10, 9, 8, 7), nrow = 2, ncol = 2)
42+
# cm <- makeCacheMatrix(m1)
43+
# cacheSolve(cm) # doesn't use cache, returns solve(m1)
44+
# cacheSolve(cm) # returns cached result
45+
# cm$set(m2)
46+
# cacheSolve(cm) # doesn't use cache, returns solve(m2)
47+
# cacheSolve(cm) # returns cached result

0 commit comments

Comments
 (0)