Skip to content

Commit afb3cc3

Browse files
committed
Update cachematrix.R
1 parent 7f657dd commit afb3cc3

File tree

1 file changed

+47
-9
lines changed

1 file changed

+47
-9
lines changed

cachematrix.R

+47-9
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
3-
4-
## Write a short comment describing this function
5-
6-
makeCacheMatrix <- function(x = matrix()) {
1+
## Writing two functions that cache the inverse of a matrix
72

3+
## This function creates a special "matrix" object that can cache its inverse
4+
makeCacheMatrix <- function( m = matrix() ) {
5+
## Initializing the inverse property
6+
i <- NULL
7+
## Setting the matrix method
8+
set <- function( matrix ) {
9+
m <<- matrix
10+
i <<- NULL
11+
}
12+
## Getting the matrix method
13+
get <- function() {
14+
## Returning the matrix
15+
m
16+
}
17+
## Setting the inverse of the matrix
18+
setInverse <- function(inverse) {
19+
i <<- inverse
20+
}
21+
## Getting the inverse of the matrix
22+
getInverse <- function() {
23+
## Returning the inverse property
24+
i
25+
}
26+
## Returning a list of methods
27+
list(set = set, get = get,
28+
setInverse = setInverse,
29+
getInverse = getInverse)
830
}
931

10-
11-
## Write a short comment describing this function
32+
## This function computes the inverse of the special "matrix"
33+
## returned by makeCacheMatrix above. If the inverse has already
34+
## been calculated (and the matrix has not changed), then the cachesolve
35+
## should retrieve the inverse from the cache.
1236

1337
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
38+
## Returning matrix that is the inverse of 'x'
39+
m <- x$getInverse()
40+
## Returning the inverse if its set already
41+
if( !is.null(m) ) {
42+
message("getting cached data")
43+
return(m)
44+
}
45+
## Getting the matrix from the object
46+
data <- x$get()
47+
## Calculating the inverse by using matrix multiplication
48+
m <- solve(data) %*% data
49+
## Setting the inverse to the object
50+
x$setInverse(m)
51+
## Finally returning the matrix
52+
m
1553
}

0 commit comments

Comments
 (0)