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
64 lines (55 loc) · 1.3 KB
/
cachematrix.R
File metadata and controls
64 lines (55 loc) · 1.3 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# function creates object with get(), setInverse(), getInverse() functions
makeCacheMatrix <- function(x = matrix())
{
cached_inverse <- NULL
# returns matrix
get <- function()
{
x
}
# saves computer inverse
setInverse <- function(inverse)
{
cached_inverse <<- inverse
}
# returns cached value of inverse or NULL
getInverse <- function()
{
cached_inverse
}
list(get = get, setInverse = setInverse, getInverse = getInverse)
}
# Function returns inverse of matrix.
# If inverse isn't cached, function makes necessary calculations and save it in cache by setInvert() function of source object
cacheSolve <- function(x)
{
cached_inverse <- x$getInverse()
if(!is.null(cached_inverse))
{
message("getting cached data")
inverse <- cached_inverse
}
else
{
inverse <- solve(x$get())
x$setInverse(inverse)
}
inverse
}
########### TEST RESULTS #########################
# > mtr = matrix(1:4,2)
# > obj = makeCacheMatrix(mtr)
# > cacheSolve(obj)
# [,1] [,2]
# [1,] -2 1.5
# [2,] 1 -0.5
# > cacheSolve(obj)
# getting cached data
# [,1] [,2]
# [1,] -2 1.5
# [2,] 1 -0.5
# > cacheSolve(obj)
# getting cached data
# [,1] [,2]
# [1,] -2 1.5
# [2,] 1 -0.5