Skip to content

Commit abfdd2c

Browse files
committed
cachematrix.R
1 parent 7f657dd commit abfdd2c

File tree

1 file changed

+41
-7
lines changed

1 file changed

+41
-7
lines changed

cachematrix.R

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,49 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## The goal of this pair of functions is to cache the inverse of a matrix.
32

4-
## Write a short comment describing this function
53

6-
makeCacheMatrix <- function(x = matrix()) {
74

5+
## makeVector creates a special "matrix", which is really a matrix containing a function to
6+
## set the value of the squared matrix
7+
## get the value of the squared matrix
8+
## set the value of the inverse of the matrix
9+
## get the value of the inverse of the matrix
10+
11+
makeCacheMatrix <- function(m = matrix()) {
12+
inv <- NULL
13+
set <- function(y) {
14+
m <<- y
15+
inv <<- NULL
16+
}
17+
get <- function() m
18+
setinverse <- function(inverse) inv <<- inverse
19+
getinverse <- function() inv
20+
21+
list(set = set, get = get,
22+
setinverse = setinverse,
23+
getinverse = getinverse)
824
}
925

1026

11-
## Write a short comment describing this function
27+
## cacheSolve function calculates the inverse of the matrix created with the makeCacheMatrix function.
28+
## However, it first checks to see if the inverse of the matrix has already been calculated.
29+
## If so, it gets the inverse of the matrix from the cache and skips the computation.
30+
## Otherwise, it calculates the inverse of the matrix and sets the value of the inverse in the cache via the setinverse function.
1231

13-
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
32+
cacheSolve <- function(m) {
33+
## Return a matrix that is the inverse of 'm'
34+
inv <- m$getinverse()
35+
if(!is.null(inv)) {
36+
message("getting cached data")
37+
return(inv)
38+
}
39+
data <- m$get()
40+
inv <- solve(data)
41+
m$setinverse(inv)
42+
inv
43+
1544
}
45+
46+
47+
## This code is used just for test purpose
48+
## m <- makeCacheMatrix(matrix(1:4,2,2))
49+
## t <- cacheSolve(m)

0 commit comments

Comments
 (0)