Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 573bc4f

Browse files
committed
updated cachematrix.R considering my solution to the assignment.
1 parent 7f657dd commit 573bc4f

File tree

1 file changed

+54
-8
lines changed

1 file changed

+54
-8
lines changed

cachematrix.R

Lines changed: 54 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,61 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## JHDS Certification - R Programming
2+
##
3+
## Rodrigo Duran :: https://github.com/rduran/ProgrammingAssignment2
4+
##
5+
## Assignment: Caching the Inverse of a Matrix
6+
##
7+
## Computing the inverse of a square matrix can be done with the solve function
8+
## in R. For example, if X is a square invertible matrix, then solve(X) returns
9+
## its inverse.
10+
##
11+
## For this assignment, assume that the matrix supplied is always invertible.
312

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

14+
##
15+
## makeCacheMatrix: This function creates a special "matrix" object that can cache
16+
## its inverse
17+
##
618
makeCacheMatrix <- function(x = matrix()) {
7-
19+
cached <<- NULL
20+
21+
## makes sure that cached element is empty
22+
set <- function(y) {
23+
x <<- y
24+
cached <<- NULL
25+
}
26+
27+
## Retreives the original matrix
28+
get <- function() x
29+
30+
## Caches the inverse
31+
setInverse <- function(x) cached <<- x
32+
33+
## Retreives the cached value
34+
getInverse <- function() cached
35+
36+
## Expose the API for caching
37+
list( set = set, get = get, setInverse = setInverse,
38+
getInverse = getInverse)
839
}
940

10-
11-
## Write a short comment describing this function
12-
41+
##
42+
## cacheSolve: This function computes the inverse of the special "matrix"
43+
## returned by makeCacheMatrix above. If the inverse has already
44+
## been calculated (and the matrix has not changed), then the
45+
## cachesolve should retrieve the inverse from the cache.
46+
##
1347
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
48+
## Retrieves the cached inverse matrix
49+
inv_m <- x$getInverse()
50+
if( !is.null(inv_m) ) {
51+
message("getting cached data")
52+
return(inv_m)
53+
}
54+
55+
## If the cached inverse matrix is null, proceed with calculation
56+
m <- x$get() # Retrieves the orignal matrix
57+
inv_m <- solve(m, ...) # Calculates the inverse matrix
58+
x$setInverse(inv_m) # Caches the inverse matrix
59+
60+
inv_m
1561
}

0 commit comments

Comments
 (0)