Skip to content

Commit 7a14be0

Browse files
committed
Programming Assignment 2
1 parent 7f657dd commit 7a14be0

File tree

1 file changed

+52
-6
lines changed

1 file changed

+52
-6
lines changed

cachematrix.R

+52-6
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
31

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

6-
makeCacheMatrix <- function(x = matrix()) {
3+
## makeCacheMatrix starts savinf null default values for some variables.
4+
# Then a few functions are defined inside for saving the input matrix and inverse,
5+
# and for returning the input matrix and getting the cached values.
6+
7+
8+
makeCacheMatrix <- function(in_mat = matrix()) {
9+
10+
#Save initial default Null values
11+
saved_inv<-NULL
12+
saved_mat<-NULL
13+
14+
#Function for saving Matrix and Inverse in cache
15+
setinv<-function(y){
16+
saved_mat <<- y
17+
saved_inv <<- solve(y)
18+
}
19+
20+
#self explanatory functions
21+
get_input_matrix <- function() in_mat
22+
23+
get_saved_matrix <-function() saved_mat
24+
25+
getinv <-function() saved_inv
26+
27+
list(setinv = setinv, get_input_matrix = get_input_matrix,
28+
get_saved_matrix=get_saved_matrix, getinv=getinv)
729

830
}
931

1032

11-
## Write a short comment describing this function
33+
## cacheSolve starts retrieving the input and cached matrix.
34+
# It compares both of them and if they are the same it retrieves the cached
35+
# inverse. If they are dissimilar it means the matrix has changed so it calculates
36+
# the inverse and saves it in cache.
1237

1338
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
39+
40+
#retrieve input matrix and cached matrix
41+
inputmat <- x$get_input_matrix()
42+
savedmat <- x$get_saved_matrix()
43+
44+
#retrieve cached inverse
45+
inv<- x$getinv()
46+
47+
48+
#compare cached and input matrix, copy inverse when appropriate
49+
if(!is.null(inv) && identical(inputmat, savedmat) ) {
50+
message("The inverse of this matrix has been calculated.
51+
Let's get the damn thing:")
52+
return(inv)
53+
}else{
54+
message("The inverse of this matrix is not in cache.
55+
I'll calculate it explicitly and save it.")
56+
57+
newinv<-x$setinv(inputmat)
58+
newinv
59+
}
60+
1561
}

0 commit comments

Comments
 (0)