forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
68 lines (57 loc) · 2.5 KB
/
Copy pathcachematrix.R
File metadata and controls
68 lines (57 loc) · 2.5 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
#makecachematrix fucntion is created to build a new matrix which can cache its inverse.
# This function takes an input value to build a matrix.
# It will set the matrix to that initial value, get the value as well.
# It will set the Inverse matrix and gets it as well.
# This will enable the matrix object to cache its own inverse matrix.
makeCacheMatrix <- function(x = matrix()) { #Creating the function
inverse_matrix <- NULL # Setting it to NULL
set <- function(y) { #Setting the value of the matrix
x <<- y
inverse_matrix <<- NULL
}
get <- function() x #Getting the value of the matrix
setinverse <- function(inverse) inverse_matrix <<- inverse #Setting the Inverse of the matrix
getinverse <- function() inverse_matrix #Getting the Inverse of the matrix
list(set = set, get = get, setinverse = setinverse, getinverse = getinverse)
}
## Write a short comment describing this function
# Cachesolve function pulls the output of the makeCacheMatrix and uses it as the input and checks if there is any value for Inverse matrix.
# If it finds a value for it it will skip the computation but if it is empty the calculates the inverse and sets the value in the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inverse_matrix <- x$getinverse()
if (!is.null(inverse_matrix)) { #It will get the input from the cache
message("Getting cached inverse matrix")
return(inverse_matrix)
}
inversedata <- x$get()
inverse_matrix <- solve(inversedata, ...)
x$setinverse(inverse_matrix) #It will set the value of the inverse matrix in cache
return(inverse_matrix)
}
#OUTPUT:
# > matrix2 <- matrix(1:4, 2, 2)
# > matrix2
# [,1] [,2]
# [1,] 1 3
# [2,] 2 4
# > matrix_cache <- makeCacheMatrix(matrix2)
# > matrix_cache$get()
# [,1] [,2]
# [1,] 1 3
# [2,] 2 4
# > matrix_cache$getinverse()
# NULL
# > cacheSolve(matrix_cache)
# [,1] [,2]
# [1,] -2 1.5
# [2,] 1 -0.5
# > cacheSolve(matrix_cache)
# Getting cached inverse matrix
# [,1] [,2]
# [1,] -2 1.5
# [2,] 1 -0.5
# >