Skip to content

Commit 658a8f1

Browse files
committed
Implemented cached matrix inversion
1 parent 7f657dd commit 658a8f1

File tree

1 file changed

+44
-6
lines changed

1 file changed

+44
-6
lines changed

cachematrix.R

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,53 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Functions for computing cached matrix inversions
32

4-
## Write a short comment describing this function
3+
## makeCacheMatrix creates a cached matrix object for storing cached inversion results
4+
## Parameter x is the initial matrix stored in the cache
55

66
makeCacheMatrix <- function(x = matrix()) {
7-
7+
inv <- NULL
8+
9+
# Sets the matrix whose inverse is cached
10+
set <- function(y) {
11+
x <<- y
12+
inv <<- NULL
13+
}
14+
15+
# Gets the matrix whose inverse is cached
16+
get <- function() {
17+
x
18+
}
19+
20+
# Sets the inverse value of the matrix
21+
setinverse <- function(i) {
22+
inv <<- i
23+
}
24+
25+
# Gets the inverse value of the matrix
26+
getinverse <- function() {
27+
inv
28+
}
29+
30+
# Return the object as a vector of functions
31+
list(set=set, get=get, setinverse=setinverse, getinverse=getinverse)
832
}
933

1034

11-
## Write a short comment describing this function
35+
## cacheSolve computes the inverse of the given matrix x, using cached results when available
36+
## Parameter x must be a cached matrix object created using makeCacheMatrix()
1237

1338
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
39+
# Check if solution is cached
40+
inv <- x$getinverse()
41+
if (!is.null(inv)) {
42+
# Yes, it was cached, return it
43+
return(inv)
44+
}
45+
46+
# No, solution not yet cached, compute it now and cache it
47+
data <- x$get()
48+
inv <- solve(data, ...)
49+
x$setinverse(inv)
50+
51+
# Return the inverse matrix
52+
inv
1553
}

0 commit comments

Comments
 (0)