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
61 lines (55 loc) · 1.69 KB
/
cachematrix.R
File metadata and controls
61 lines (55 loc) · 1.69 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
## Matrix inversion is usually a costly computation
## Therefore sometimes we may take benefit of caching
## the inverse of the matrix rather than compute it each time.
#
# Example of run:
# x = rbind(c(1, -1/4, 1/3), c(-1/4, 1, 1), c(1, 1/2, 1/2))
# m <- makeCacheMatrix(x)
# cacheSolve(m)
# [,1] [,2] [,3]
# [1,] 0.000000 -0.4444444 0.8888889
# [2,] -1.714286 -0.2539683 1.6507937
# [3,] 1.714286 1.1428571 -1.42857
#
# cacheSolve(m)
# getting cached data
# [,1] [,2] [,3]
# [1,] 0.000000 -0.4444444 0.8888889
# [2,] -1.714286 -0.2539683 1.6507937
# [3,] 1.714286 1.1428571 -1.4285714
#
## The function "makeCacheMatrix" creates a list containing 4 function that enable us to:
# 1.set the value of the matrix ==> set
# 2.get the value of the matrix ==> get
# 3.set the value of the inverse of the matrix ==> setinverse
# 4.get the value of the inverse of the matrix ==> getinverse
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinv <- function(solve) inv <<- solve
getinv <- function() inv
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
## This function get us the inverse of a "special matrix"
## that we got from calling "makeCacheMatrix"
# If the inverse has already been calculated ,
# than the answer will be given from the cache.
# This function assumes that the matrix is invertible.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data, ...)
x$setinv(inv)
inv
}