forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
53 lines (42 loc) · 1.59 KB
/
cachematrix.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
## This file contains a set of functions for computing the inverse of a matrix. Furthermore,
## it also contains a function to check whether the inverse has already been previously calculated.
## If the inverse has already been previously calculated, the cached result is returned.
##
## Jack Elendil B. Lagare
## This function initializes a new matrix object.
makeCacheMatrix <- function(x = matrix()) {
m <- NULL; # This is the variable storing the calculated inverse of the matrix provided.
# Resets to NULL whenever a new matrix is initialized.
# Saves the input matrix and saves it. Resets the value of m into NULL.
set <- function(y){
x <<- y
m <<- NULL
}
# Returns the value of the current input matrix
get <- function(){
x
}
# Saves the inverse of the input matrix
setinverse <- function(inverse){
m <<- inverse
}
# Retrieves the inverse of the input matrix
getinverse <- function(){
m
}
# Lists all the available operations you can perform on the created object
list(get = get,setinverse = setinverse, getinverse = getinverse)
}
## This function checks whether a cached result of the inverse already exists. If not, calculate inverse.
cacheSolve <- function(x, ...) {
m <- x$getinverse() # Retrieves the inverse
# If result already exists, just return result
if(!is.null(m)){
message("getting cached data")
return (m);
}
data <- x$get() # Get the input matrix
m <- solve(data) # Calculate the inverse
x$setinverse(m) # Store the result
m # Return the result
}