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

Skip to content

Commit bc359ce

Browse files
committed
Working code tested on invertable matrices
1 parent 7f657dd commit bc359ce

File tree

1 file changed

+29
-10
lines changed

1 file changed

+29
-10
lines changed

cachematrix.R

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,34 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
5-
1+
## Create a matrix and lexically scoped function
2+
## Follow the code in the example for this assignment
3+
## ???
4+
## Profit!
5+
## Pass in matrix, return list with setters and getters
6+
## test on example from forum: matrix(c(1,1,1,3,4,3,3,3,4),3,3)
7+
## more tests at https://class.coursera.org/rprog-009/forum/thread?thread_id=164
68
makeCacheMatrix <- function(x = matrix()) {
7-
9+
invertedMatrix <- NULL
10+
set <- function(y) {
11+
x <<- y
12+
invertedMatrix <<- NULL
13+
}
14+
get <- function() x
15+
setinverse <- function(inverse) invertedMatrix <<- inverse
16+
getinverse <- function() invertedMatrix
17+
list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) ## list with function closures!
818
}
919

10-
11-
## Write a short comment describing this function
12-
20+
## Use the R solve() function to invert a matrix - return prior results if cached
1321
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
22+
## Return a matrix that is the inverse of 'x'
23+
## NO CHECKING for invertable matrix
24+
invertedMatrix <- x$getinverse()
25+
if (!is.null(invertedMatrix)) { ## if not null, we found a cache hit
26+
message("getting cached matrix")
27+
return(invertedMatrix)
28+
} else { ## cache miss; else clause clearer IMO
29+
invertedMatrix <- solve(x$get()) ## execute the function, don't return it
30+
x$setinverse(invertedMatrix) ## now set the cache so we don't recalculate on another invocation
31+
return(invertedMatrix)
32+
}
1533
}
34+

0 commit comments

Comments
 (0)