Skip to content

Commit 2e4b013

Browse files
committed
Update cachematrix.R
1 parent c4ad4db commit 2e4b013

File tree

1 file changed

+42
-5
lines changed

1 file changed

+42
-5
lines changed

cachematrix.R

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,51 @@
1-
## The function below creates a matrix
2-
1+
## This pair of functions builds cache solution for inverting matrices
2+
##
3+
## First function below creates a special matrix
34

45
makeCacheMatrix <- function(x = matrix()) {
5-
6+
TheOne <- NULL
7+
set <- function(y) {
8+
x <<- y
9+
TheOne <<- NULL
10+
}
11+
get <- function() x
12+
setinverse <- function(solve) TheOne <<- solve
13+
getinverse <- function() TheOne
14+
list(set = set, get = get,
15+
setinverse = setinverse,
16+
getinverse = getinverse)
617
}
718

819

9-
## This function inverses matrix, checking if this is already done.
20+
## Next function inverses matrix, checking if this is already done.
1021
## If so, it takes and returns cached result
1122

1223
cacheSolve <- function(x, ...) {
13-
## Return a matrix that is the inverse of 'x'
24+
TheOne <- x$getinverse()
25+
if(!is.null(TheOne)) {
26+
message("Getting data from cache")
27+
return(TheOne)
28+
}
29+
data <- x$get()
30+
TheOne <- solve(data, ...)
31+
x$setinverse(TheOne)
32+
TheOne
1433
}
34+
35+
## Extra code to check how the above pair works:
36+
37+
## Creates simple 2x2 matrix
38+
c=rbind(c(1, -1/4), c(-1/4, 1))
39+
## prints it
40+
c
41+
## inverts it and prints the result
42+
solve(c)
43+
44+
## Creates special matrix with cache ability
45+
Mat<-makeCacheMatrix(c)
46+
## Inverts it
47+
cacheSolve(Mat)
48+
## Inverts it again, this time through cache
49+
cacheSolve(Mat)
50+
51+
## Works!

0 commit comments

Comments
 (0)