Skip to content

Commit b2f7a23

Browse files
committed
Matrix and invertible function
1 parent 5db54a7 commit b2f7a23

File tree

1 file changed

+57
-10
lines changed

1 file changed

+57
-10
lines changed

cachematrix.R

Lines changed: 57 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,63 @@
1-
##Second GIT Project
2-
## Put comments here that give an overall description of what your
3-
## functions do
4-
5-
## Write a short comment describing this function
6-
71
makeCacheMatrix <- function(x = matrix()) {
8-
2+
## @x: a square invertible matrix
3+
## return: a list containing functions to
4+
## 1. set the matrix
5+
## 2. get the matrix
6+
## 3. set the inverse
7+
## 4. get the inverse
8+
## this list is used as the input to cacheSolve()
9+
10+
inv = NULL
11+
set = function(y) {
12+
# use `<<-` to assign a value to an object in an environment
13+
# different from the current environment.
14+
x <<- y
15+
inv <<- NULL
16+
}
17+
get = function() x
18+
setinv = function(inverse) inv <<- inverse
19+
getinv = function() inv
20+
list(set=set, get=get, setinv=setinv, getinv=getinv)
921
}
1022

23+
cacheSolve <- function(x, ...) {
24+
## @x: output of makeCacheMatrix()
25+
## return: inverse of the original matrix input to makeCacheMatrix()
26+
27+
inv = x$getinv()
28+
29+
# if the inverse has already been calculated
30+
if (!is.null(inv)){
31+
# get it from the cache and skips the computation.
32+
message("getting cached data")
33+
return(inv)
34+
}
35+
36+
# otherwise, calculates the inverse
37+
mat.data = x$get()
38+
inv = solve(mat.data, ...)
39+
40+
# sets the value of the inverse in the cache via the setinv function.
41+
x$setinv(inv)
42+
43+
return(inv)
44+
}
1145

12-
## Write a short comment describing this function
46+
##Test function
1347

14-
cacheSolve <- function(x, ...) {
15-
## Return a matrix that is the inverse of 'x'
48+
test = function(mat){
49+
## @mat: an invertible matrix
50+
51+
temp = makeCacheMatrix(mat)
52+
53+
start.time = Sys.time()
54+
cacheSolve(temp)
55+
dur = Sys.time() - start.time
56+
print(dur)
57+
58+
start.time = Sys.time()
59+
cacheSolve(temp)
60+
dur = Sys.time() - start.time
61+
print(dur)
1662
}
63+

0 commit comments

Comments
 (0)