Skip to content

Commit b10712e

Browse files
committed
implemented the functions makeCacheMatrix() and cacheSolve()
1 parent 7f657dd commit b10712e

File tree

1 file changed

+63
-6
lines changed

1 file changed

+63
-6
lines changed

cachematrix.R

Lines changed: 63 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,72 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Matrix inversion is usually a costly computation and there may be some benefit
2+
## to caching the inverse of a matrix rather than computing it repeatedly.
3+
## These two functions, makeCacheMatrix() and cacheSolve() are used to cache the
4+
## inverse of a matrix
35

4-
## Write a short comment describing this function
6+
## This function creates a special "matrix" object that can cache its inverse
57

68
makeCacheMatrix <- function(x = matrix()) {
7-
9+
i <- NULL
10+
set <- function(y) {
11+
x <<- y
12+
i <<- NULL
13+
}
14+
get <- function() x
15+
setinverse <- function(inv) i <<- inv
16+
getinverse <- function() i
17+
list(set = set, get = get,
18+
setinverse = setinverse,
19+
getinverse = getinverse)
820
}
921

1022

11-
## Write a short comment describing this function
23+
## This function computes the inverse of the special "matrix" returned by
24+
## makeCacheMatrix above. If the inverse has already been calculated
25+
## (and the matrix has not changed), then cacheSolve should retrieve the
26+
## inverse from the cache
1227

1328
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
29+
i <- x$getinverse()
30+
if(!is.null(i)) {
31+
message("getting cached data")
32+
return(i)
33+
}
34+
data <- x$get()
35+
i <- solve(data, ...)
36+
x$setinverse(i)
37+
i
1538
}
39+
40+
# Sample output
41+
#
42+
# > cacheMatrix = makeCacheMatrix(m1)
43+
# > print(cacheSolve(cacheMatrix))
44+
# [,1] [,2]
45+
# [1,] 0.6 -0.2
46+
# [2,] -0.7 0.4
47+
# > print(cacheSolve(cacheMatrix))
48+
# getting cached data
49+
# [,1] [,2]
50+
# [1,] 0.6 -0.2
51+
# [2,] -0.7 0.4
52+
# > print(cacheSolve(cacheMatrix))
53+
# getting cached data
54+
# [,1] [,2]
55+
# [1,] 0.6 -0.2
56+
# [2,] -0.7 0.4
57+
# >
58+
# > cacheMatrix$set(m2)
59+
# > print(cacheSolve(cacheMatrix))
60+
# [,1] [,2]
61+
# [1,] 0.3 -0.1
62+
# [2,] -0.1 0.1
63+
# > print(cacheSolve(cacheMatrix))
64+
# getting cached data
65+
# [,1] [,2]
66+
# [1,] 0.3 -0.1
67+
# [2,] -0.1 0.1
68+
# > print(cacheSolve(cacheMatrix))
69+
# getting cached data
70+
# [,1] [,2]
71+
# [1,] 0.3 -0.1
72+
# [2,] -0.1 0.1

0 commit comments

Comments
 (0)