Skip to content

Commit a3c4108

Browse files
committed
initial commit of cachematrix.R
1 parent 7f657dd commit a3c4108

File tree

1 file changed

+47
-2
lines changed

1 file changed

+47
-2
lines changed

cachematrix.R

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,60 @@
11
## Put comments here that give an overall description of what your
22
## functions do
33

4+
# Usage:
5+
# > M <- matrix(c(1,2,3,4),2,2)
6+
# > NN <- makeCacheMatrix()
7+
# > NN$set(M)
8+
# > NN$get()
9+
# [,1] [,2]
10+
# [1,] 1 3
11+
# [2,] 2 4
12+
# > NN$getinverse()
13+
# NULL
14+
# > cacheSolve(NN)
15+
# [,1] [,2]
16+
# [1,] -2 1.5
17+
# [2,] 1 -0.5
18+
# > NN$getinverse()
19+
# [,1] [,2]
20+
# [1,] -2 1.5
21+
# [2,] 1 -0.5
22+
# > cacheSolve(NN)
23+
# getting cached data
24+
# [,1] [,2]
25+
# [1,] -2 1.5
26+
# [2,] 1 -0.5
27+
428
## Write a short comment describing this function
529

630
makeCacheMatrix <- function(x = matrix()) {
31+
inverse_matrix <- NULL
32+
set <- function(y) {
33+
a_matrix <<- y
34+
inverse_matrix <<- NULL
735

36+
}
37+
get <- function() a_matrix
38+
setinverse <- function(the_inverse_matrix) inverse_matrix <<- the_inverse_matrix
39+
getinverse <- function() inverse_matrix
40+
list(set = set, get = get,
41+
setinverse = setinverse,
42+
getinverse = getinverse)
843
}
944

1045

1146
## Write a short comment describing this function
1247

1348
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
49+
## Return a matrix that is the inverse of 'x'
50+
## to be precise, 'x' is a composite object built up by a call to makeCacheMatrix()
51+
inverse_matrix <- x$getinverse()
52+
if(!is.null(inverse_matrix)) {
53+
message("getting cached data")
54+
return(inverse_matrix)
55+
}
56+
the_matrix_elements <- x$get()
57+
inverse_matrix <- solve(the_matrix_elements, ...)
58+
x$setinverse(inverse_matrix)
59+
inverse_matrix
60+
}

0 commit comments

Comments
 (0)