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 (44 loc) · 1.18 KB
/
Copy pathcachematrix.R
File metadata and controls
50 lines (44 loc) · 1.18 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
## These functions calculate and cache the inverse
## of a matrix
## This function caches the inverse matrix and
## acts as a special vector
makeCacheMatrix <- function(x = matrix()) {
inverse_matrix <- NULL
set <- function(y) {
x <<- y
inverse_matrix <<- NULL
}
get <- function() x
setinverse <- function(inverse) inverse_matrix <<- inverse
getinverse <- function() inverse_matrix
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## This function solves the inverse matrix
## We assume the given matrix is square and
## invertible
cacheSolve <- function(x, ...) {
im <- x$getinverse()
if(!is.null(im)) {
message("getting cached data")
return(im)
}
data <- x$get()
im <- solve(data, ...)
x$setinverse(im)
## Return a matrix that is the inverse of 'x'
im
}
## I tested the functions with the following:
## > A <- matrix(c(0,1,1,1), nrow = 2, ncol = 2)
## > iA <- makeCacheMatrix(A)
## > cacheSolve(iA)
## [,1] [,2]
## [1,] -1 1
## [2,] 1 0
## > cacheSolve(iA)
## getting cached data
## [,1] [,2]
## [1,] -1 1
## [2,] 1 0