forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachematrix.R
84 lines (69 loc) · 2.38 KB
/
cachematrix.R
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
## makeCacheMatrix: create a special matrix object "m" that can cache its inverse
makeCacheMatrix <- function(x = matrix()) {
m <- NULL # assign null object to name variable of matrix
set <- function(y) {
x <<- y # use <<- operator to assign y object to x
m <<- NULL # use <<- operator to assign NULL object to m
}
get <- function() x
setinverse <- function(inverse) m <<- inverse
getinverse <- function() m
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## Write a short comment describing this function
## cacheSolve: computes and returns the inverse of matrix "m"
cacheSolve <- function(x, ...) {
m <- x$getinverse() # try to get inverse matrix from cache
# if m is cached already just return it ...
if(!is.null(m)) {
message("getting cached data")
return(m) # return inverse matrix from cache
}
# ... if m was empty obtain original matrix and write into
# variable "data"
data <- x$get()
m <- solve(data) # then get inverse of matrix data and write to m
x$setinverse(m)
m # return inverse matrix from data
}
## RUNNING A SESSION USING THE TWO FUNCTIONS
## read file
#> source('cachematrix.R')
## Create a simple 3x3 matrix.
#> A=makeCacheMatrix(matrix(c(1,0,1,0,2,1,1,1,1),nrow=3,ncol=3))
## Check whether the matrix was created correctly:
#> A$get()
# [,1] [,2] [,3]
#[1,] 1 0 1
#[2,] 0 2 1
#[3,] 1 1 1
# Try getting the inverse of A:
#> A$getinverse()
#NULL
## It failed because the code looked for it in the cache. The inverse
## of A has not been created yet because "cacheSolve" has not been run
## yet.
## run cacheSolve(A)to obtain the inverse of A:
#> cacheSolve(A)
# [,1] [,2] [,3]
#[1,] -1 -1 2
#[2,] -1 0 1
#[3,] 2 1 -2
# Repeating the command now yields the inverse of A:
#> A$getinverse()
# [,1] [,2] [,3]
#[1,] -1 -1 2
#[2,] -1 0 1
#[3,] 2 1 -2
## Repeating cacheSolve now retrieves the inverse of A from cache:
#> cacheSolve(A)
#getting cached data
# [,1] [,2] [,3]
#[1,] -1 -1 2
#[2,] -1 0 1
#[3,] 2 1 -2