Skip to content

Commit db6d076

Browse files
committed
Working inverse matrixfunctions and cache
1 parent 3ee94a7 commit db6d076

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

cachematrix.R

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,46 @@
44
## Write a short comment describing this function
55

66
makeCacheMatrix <- function(x = matrix()) {
7-
7+
# first make a local variable `im` for the inverse matrx
8+
im <- NULL
9+
# enable setting of global env variables
10+
set <- function(y) {
11+
## scope matrix to a global env variable `x`
12+
x <<- y
13+
## scope an empty global env variable `im`
14+
im <<- NULL
15+
}
16+
## return original matrix
17+
get <- function() {x}
18+
## Set `im` to be calculated inversematrix in global environment lexical scope by using `<<-`
19+
setinverse <- function(inversematrix) {
20+
im <<- inversematrix
21+
}
22+
# retrieve the inverse matrix of x
23+
getinverse <- function() {im}
24+
list(set = set, get = get, setinverse = setinverse, getinverse = getinverse)
825
}
926

1027

1128
## Write a short comment describing this function
29+
## assume matrix `x` is always invertable
1230

1331
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
32+
## Return a matrix that is the inverse of 'x'
33+
# `x` is a matrix
34+
# `ix` is inverse of matrix
35+
36+
# `x` is makeCacheMatrix object
37+
ix <- x$getinverse()
38+
if (!is.null(ix)) {
39+
message("getting cached data")
40+
return(ix)
41+
}
42+
43+
## inverse the matrix
44+
message("calculating inverse and caching result")
45+
matrix <- x$get()
46+
ix <- solve(matrix, ...)
47+
x$setinverse(ix)
48+
ix
49+
}

0 commit comments

Comments
 (0)