Skip to content

Commit 8652e44

Browse files
authored
Update cachematrix.R
1 parent 7f657dd commit 8652e44

File tree

1 file changed

+67
-4
lines changed

1 file changed

+67
-4
lines changed

cachematrix.R

Lines changed: 67 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,78 @@
11
## Put comments here that give an overall description of what your
22
## functions do
33

4-
## Write a short comment describing this function
4+
## Encapsulates the inverse of the given matrix using caching.
55

6-
makeCacheMatrix <- function(x = matrix()) {
6+
makeCacheMatrix <- function( m = matrix() ) {
77

8+
## Initialize the inverse property
9+
inv <- NULL
10+
11+
## Method to set the matrix
12+
set <- function( matrix ) {
13+
m <<- matrix
14+
inv <<- NULL
15+
}
16+
17+
## Method the get the matrix
18+
get <- function() {
19+
## Return the matrix
20+
m
21+
}
22+
23+
## Method to set the inverse of the matrix
24+
setInverse <- function(inverse) {
25+
inv <<- inverse
26+
}
27+
28+
## Method to get the inverse of the matrix
29+
getInverse <- function() {
30+
## Return the inverse property
31+
inv
32+
}
33+
34+
## Return a list of the methods
35+
list(set = set, get = get,
36+
setInverse = setInverse,
37+
getInverse = getInverse)
838
}
939

1040

11-
## Write a short comment describing this function
41+
42+
## Produces the inverse of the matrix being returned by the previous function (makeCacheMatrix).
43+
## If the inverse is already computed, it will retuen the already computed value.
1244

1345
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
46+
47+
## Return a matrix that is the inverse of 'x'
48+
A <- x$getInverse()
49+
## Just return the inverse if its already set
50+
if( !is.null(A) ) {
51+
message("getting cached data")
52+
return(A)
53+
}
54+
55+
## Get the matrix from our object
56+
data <- x$get()
57+
58+
## Calculate the inverse using matrix multiplication
59+
A <- solve(data)
60+
61+
## Set the inverse to the object
62+
x$setInverse(A)
63+
64+
## Return the matrix
65+
A
1566
}
67+
68+
69+
#example
70+
#as<-matrix(1:4,2,2)
71+
#second<-makeCacheMatrix(as)
72+
#print(second$inv)
73+
#cacheSolve(second)
74+
#output
75+
#NULL
76+
# [,1] [,2]
77+
#[1,] -2 1.5
78+
#[2,] 1 -0.5

0 commit comments

Comments
 (0)