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
54 lines (43 loc) · 1.43 KB
/
Copy pathcachematrix.R
File metadata and controls
54 lines (43 loc) · 1.43 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
## Coursera R Programming - Assignment 2
## This script contains a set of functions to define a
## matrix-type object whose inverse can be cached.
## When extracting the inverse, an attempt is made to
## retrieve cached data. If nothing has been stored, the
## inverse is calculated from scratch.
## Code inspired by vector mean example in assignment instructions
## This function defines a matrix-type object
## capable of caching its inverse.
makeCacheMatrix <- function(x = matrix()) {
#Inverse of the matrix
xInv <- NULL
#Function to set the matrix
set <- function(y){
x <<- y
xInv <<- NULL
}
#Function to get the matrix
get <- function() x
#Function to set the inverse
setinv <- function(inv) xInv <<- inv
#Function to get the inverse
getinv <- function() xInv
#In reality, all we need is a vector of functions
list(set = set, get = get, setinv = setinv, getinv = getinv)
}
## Function to compute the inverse of a "cacheMatrix" object.
## It first attempts to retrieve the inverse from the cache.
## If NULL, it computes the inverse with the solve() function
cacheSolve <- function(x, ...) {
xInv <- x$getinv()
#Check if inverse has been previously found and cached
if(!is.null(xInv)){
message("Retrieving cached inverse...")
return(xInv)
}
#If nothing in cache, get matrix and compute inverse
matrix <- x$get()
xInv <- solve(matrix)
x$setinv(xInv)
#Return inverse
xInv
}