Skip to content

Commit cb2d27e

Browse files
committed
Assignment: Caching the Inverse of a Matrix
1 parent 7f657dd commit cb2d27e

File tree

1 file changed

+55
-2
lines changed

1 file changed

+55
-2
lines changed

cachematrix.R

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,66 @@
33

44
## Write a short comment describing this function
55

6-
makeCacheMatrix <- function(x = matrix()) {
6+
### Jairo's comments
7+
8+
### Matrix inversion is usually a costly computation, if there is need to compute many times
9+
### the same, store the result of inverse of a matrix in the cache and return the result
10+
### when need is more efficient than compute it repeatedly.
11+
12+
### following two functions are used to cache the inverse of a matrix.
13+
14+
### makeCacheMatrix creates a matrix object that can cache its inverse
715

16+
makeCacheMatrix <- function(x = matrix()) {
17+
## Initialize the inverse property
18+
inv <- NULL
19+
20+
### set the value of the matrix
21+
set <- function(y) {
22+
x <<- y
23+
inv <<- NULL
24+
}
25+
26+
### get the value of the matrix
27+
get <- function() x
28+
29+
### set the value of inverse of the matrix
30+
setinverse <- function(inverse) inv <<- inverse
31+
32+
### get the value of inverse of the matrix
33+
getinverse <- function() inv
34+
35+
### Return list of the methods
36+
list(set=set, get=get, setinverse=setinverse, getinverse=getinverse)
837
}
938

1039

1140
## Write a short comment describing this function
1241

42+
### Jairo's comments
43+
44+
### This function returns the inverse of the matrix.
45+
### 1. It first checks if the inverse has already been computed. If exist, it returns the result
46+
### and skips the computation.
47+
### 2. If not, it computes the inverse, stores the value in the cache via setinverse function.
48+
1349
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
50+
## Return a matrix that is the inverse of 'x'
51+
inv <- x$getinverse()
52+
53+
## If the inverse already set, return it
54+
if(!is.null(inv)) {
55+
message("getting cached data.")
56+
return(inv)
57+
}
58+
59+
## Get the matrix from our object
60+
data <- x$get()
61+
62+
## Compute the inverse using matrix multiplication
63+
inv <- solve(data)
64+
65+
## Set the value to the object and return it
66+
x$setinverse(inv)
67+
inv
1568
}

0 commit comments

Comments
 (0)