Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5d2725e

Browse files
committed
Update cache matrix code, add test found at
http://masterr.org/r/how-to-cache-a-matrix-inversion-in-r/
1 parent 05cf417 commit 5d2725e

File tree

2 files changed

+22
-16
lines changed

2 files changed

+22
-16
lines changed

cachematrix.R

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,20 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## This function creates a special "matrix" object
5-
## that can cache its inverse.
1+
## This function creates a special "matrix" object that can cache its inverse.
62

73
makeCacheMatrix <- function(x = matrix()) {
84
matrix <- NULL
9-
set <- function(y) {
5+
set <- function(y) { #set is a function to set the value of inverse
106
x <<- y ## search through parent environment first for a value for y and assign to x
117
inverse <<- NULL ## set the inverse to null, unless it already exists
128
}
13-
get <- function() x
9+
get <- function() x #get is a function to get the value of the matrix
1410
setinverse <- function(inverse) x <<- inverse #set the inverse value
1511
getinverse <- function() x #get the inverse value
16-
list(set = set, get = get,
12+
list(set = set, get = get, #create a list with the values of each function
1713
setinverse = setinverse,
1814
getinverse = getinverse)
19-
}
2015
}
2116

22-
## This function computes the inverse of the special
23-
## "matrix" returned by `makeCacheMatrix` above.
24-
## Computing the inverse of a square matrix can be done with the `solve`
25-
## function in R.
26-
## n is the inverted matrix
17+
## cacheSolve calculates the inverse of the “matrix” returned by makeCacheMatrix()
2718
cacheSolve <- function(x, ...) {
2819
## Return a matrix that is the inverse of 'x'
2920
n <- x$getinverse()
@@ -32,7 +23,7 @@ cacheSolve <- function(x, ...) {
3223
return(n) #return the cached inverted matrix if it already exists
3324
}
3425
data <- x$get() #if we don't have a in existing inverted matrix, create one
35-
n <- solve(data, ...)
26+
n <- solve(data, ...) #use solve() to find the inverse
3627
x$setinverse(n)
37-
n
28+
n #resturn the inverse
3829
}

test_assignment2.R

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
test = function(mat){
2+
## @mat: an invertible matrix
3+
4+
temp = makeCacheMatrix(mat)
5+
6+
start.time = Sys.time()
7+
cacheSolve(temp)
8+
dur = Sys.time() - start.time
9+
print(dur)
10+
11+
start.time = Sys.time()
12+
cacheSolve(temp)
13+
dur = Sys.time() - start.time
14+
print(dur)
15+
}

0 commit comments

Comments
 (0)