Skip to content

Commit fb3bd02

Browse files
authored
Add files via upload
My solutions to the week2 programming assignment
1 parent 7f657dd commit fb3bd02

File tree

1 file changed

+71
-15
lines changed

1 file changed

+71
-15
lines changed

cachematrix.R

Lines changed: 71 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,71 @@
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-
6-
makeCacheMatrix <- function(x = matrix()) {
7-
8-
}
9-
10-
11-
## Write a short comment describing this function
12-
13-
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
1+
## This pair of functions will provide facilities for constructing a global object for caching an invertible
2+
## matrix and its inverse
3+
4+
5+
## MakeCacheMatrix, is a function that will construct a list-object providing the input matrix with variables and methods
6+
## for global setting and getting its value and inverse
7+
8+
makeCacheMatrix <- function(x = matrix()) {
9+
i <- NULL # i is for holding the inverse
10+
set <- function(y) {
11+
x <<- y # x is updated outside the current environment
12+
i <<- NULL # i is updated outside the current environment
13+
}
14+
get <- function() x
15+
setinverse <- function(solve) i <<- solve
16+
getinverse <- function() i
17+
list(set = set,
18+
get = get,
19+
setinverse = setinverse,
20+
getinverse = getinverse)
21+
}
22+
23+
24+
## CacheSolve will access the global cache to check if an inverse of x has already been stored and return it.
25+
## If not, it will compute the inverse and store it before returning the newly computed value.
26+
27+
cacheSolve <- function(x, ...) {
28+
i <- x$getinverse()
29+
if(!is.null(i)) {
30+
message("getting cached data")
31+
return(i)
32+
}
33+
data <- x$get()
34+
i <- solve(data, ...)
35+
x$setinverse(i)
36+
i
37+
}
38+
39+
## Simple Test:
40+
## ---------------------------------------------------------
41+
## > test <- matrix(c(-1,2,3,4,-1,6,7,8,-1), nrow=3, ncol=3)
42+
## >
43+
## > test
44+
## [,1] [,2] [,3]
45+
## [1,] -1 4 7
46+
## [2,] 2 -1 8
47+
## [3,] 3 6 -1
48+
## >
49+
## > x <- makeCacheMatrix(test)
50+
## >
51+
## > cacheSolve(x)
52+
## [,1] [,2] [,3]
53+
## [1,] -0.18359375 0.1796875 0.15234375
54+
## [2,] 0.10156250 -0.0781250 0.08593750
55+
## [3,] 0.05859375 0.0703125 -0.02734375
56+
## >
57+
## > cacheSolve(x)
58+
## getting cached data
59+
## [,1] [,2] [,3]
60+
## [1,] -0.18359375 0.1796875 0.15234375
61+
## [2,] 0.10156250 -0.0781250 0.08593750
62+
## [3,] 0.05859375 0.0703125 -0.02734375
63+
## >
64+
## > x$set(test)
65+
## > cacheSolve(x)
66+
## [,1] [,2] [,3]
67+
## [1,] -0.18359375 0.1796875 0.15234375
68+
## [2,] 0.10156250 -0.0781250 0.08593750
69+
## [3,] 0.05859375 0.0703125 -0.02734375
70+
## >
71+

0 commit comments

Comments
 (0)