Skip to content

Commit f6afc49

Browse files
committed
Update cachematrix.R
1 parent 7f657dd commit f6afc49

File tree

1 file changed

+47
-8
lines changed

1 file changed

+47
-8
lines changed

cachematrix.R

Lines changed: 47 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,54 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## The following script checks the cache for an existing inversed matrix given x.
2+
## If found, the script returns the cached matrix. Otherwise, the script creates
3+
## a new inversed matrix and stores it in the cache.
34

4-
## Write a short comment describing this function
5+
storedX<<-NULL
56

67
makeCacheMatrix <- function(x = matrix()) {
7-
8+
set <<- function(y) {
9+
x <<- y
10+
inv_x <<- NULL
11+
}
12+
get <- function() x
13+
setinverse <<- function(inverse) inv_x <<-inverse
14+
getinverse <<- function() inv_x
815
}
916

10-
11-
## Write a short comment describing this function
12-
1317
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
18+
if(!is.null(storedX)) {
19+
if(identical(x,storedX)) {
20+
if (!is.null(inv_x)) {
21+
message("Retrieving inversed matrix from cache.")
22+
inv_x<<-inv_x
23+
} else {
24+
set(x)
25+
storedX<<-x
26+
message("Inversed matrix not found in cache. Creating a new inversed matrix.")
27+
require("MASS")
28+
library("MASS")
29+
makeCacheMatrix(x)
30+
inv_x <<- ginv(x)
31+
setinverse(inv_x)
32+
}
33+
} else {
34+
set(x)
35+
storedX<<-x
36+
message("Inversed matrix not found in cache. Creating a new inversed matrix.")
37+
require("MASS")
38+
library("MASS")
39+
makeCacheMatrix(x)
40+
inv_x <<- ginv(x)
41+
setinverse(inv_x)
42+
}
43+
} else {
44+
set(x)
45+
storedX<<-x
46+
message("Inversed matrix not found in cache. Creating a new inversed matrix.")
47+
require("MASS")
48+
library("MASS")
49+
makeCacheMatrix(x)
50+
inv_x <<- ginv(x)
51+
setinverse(inv_x)
52+
}
53+
inv_x
1554
}

0 commit comments

Comments
 (0)