-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.r
54 lines (48 loc) · 1.69 KB
/
code.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
54
## The following function create "matrix" object that will cache its inverse.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setInverse <- function(inverse) inv <<- inverse
getInverse <- function() inv
list(set = set,
get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## This function computes the inverse of the "matrix" makeCacheMatrix.
##If the inverse has been previously calculated and the matrix has not been changed, the inverse will be retrieved from the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getInverse()
if (!is.null(inv)) {
message("getting cached data")
return(inv)
}
mat <- x$get()
inv <- solve(mat, ...)
x$setInverse(inv)
inv
}
## First we can create a "matrix" with the numbers from 1 to 4 and create cache and retrieve the inverse
my_matrix <- makeCacheMatrix(matrix(1:4, 2, 2))
my_matrix$get()
cacheSolve(my_matrix)
cacheSolve(my_matrix)
my_matrix$getInverse()
my_matrix$getInverse()
## We can then take any random numbers and create cache and retrieve the inverse
## We will two different "matrices" with randomly chosen numbers
my_matrix <- makeCacheMatrix(matrix(c(105,95,766,83), 2, 2))
my_matrix$get()
cacheSolve(my_matrix)
cacheSolve(my_matrix)
my_matrix$getInverse()
my_matrix <- makeCacheMatrix(matrix(c(657, 6373, 546, 3), 2, 2))
my_matrix$get()
cacheSolve(my_matrix)
cacheSolve(my_matrix)
my_matrix$getInverse()