forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
50 lines (47 loc) · 1.67 KB
/
cachematrix.R
File metadata and controls
50 lines (47 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
## Caching the inverse of a matrix using the <<- operator to assign a value to an object in a different environment.
## A special object stores the matrix and it's inverse.
##
## To test ths code
## 1. Check inverse of identity matrix, should return TRUE
## m=makeCacheMatrix(matrix(c(1,0,0,0,1,0,0,0,1),nrow=3,ncol=3))
## n=makeCacheMatrix(cacheSolve(m))
## all.equal(m$get(),n$get())
##
## 2. Test that inverse of inverse are equal, both should return TRUE
## m=makeCacheMatrix(matrix(c(1,2,3,4,6,8,5,8,12),nrow=3,ncol=3))
## n=makeCacheMatrix(cacheSolve(m))
## all.equal(cacheSolve(n),m$get())
## all.equal(cacheSolve(m),n$get())
## makeCacheMatrix creates a special "matrix" object that is really a list of functions to
## 1. set the value of the matrix
## 2. get the value of the matrix
## 3. set the value of the inverse
## 4. get the value of the inverse
makeCacheMatrix <- function(x = matrix()) {
s <- NULL
set <- function(y) {
x <<- y
s <<- NULL
}
get <- function() x
setsolve <- function(solve) s <<- solve
getsolve <- function() s
list(set = set, get = get,
setsolve = setsolve,
getsolve = getsolve)
}
## cacheSolve calculates the inverse of the special matrix created with makeCacheMatrix.
## It first checks to see if the inverse has already been solved using the getsolve function.
## If so, it returns the inverse from the cache and skips the computation. Otherwise, it
## solves the inverse of the matrix and sets the value in the cache via the setsolve function.
cacheSolve <- function(x, ...) {
s <- x$getsolve()
if(!is.null(s)) {
message("getting cached data")
return(s)
}
data <- x$get()
s <- solve(data, ...)
x$setsolve(s)
s
}