forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cachematrix.R
80 lines (65 loc) · 1.81 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
makeCacheMatrix <- function(x = matrix())
{
# Initialise to NULL
cachedInverse <- NULL
# If you call get get the original matrixL
Get <- function() x
# if you call set, set the matrix and reinitialise the cached variable to Null
# we could do a check to see if its the same matrix
Set <- function(matrixToSet)
{
x <<- matrixToSet
cachedInverse <<- NULL
}
# Sets the inverse and assigns the cache
SetInverse <- function()
{
cachedInverse <<- solve(x)
}
# Gets the cached inverse
GetInverse <- function() cachedInverse
# Provides the method for the matrix
list(Get = Get, Set= Set, SetInverse = SetInverse, GetInverse = GetInverse)
}
## Write a short comment describing this function
cacheSolve <- function(x, ...)
{
val <- x$GetInverse()
if(!is.null(val))
{
message("Getting the cached value")
return(val)
}
## Set the inverse matrix - optimsied from example
x$SetInverse()
## get the value from the matrix
inverseMatrix <- x$GetInverse()
## Return value
inverseMatrix
}
cacheMatrix <- makeCacheMatrix(matrix(1:4,2,2,4))
cacheMatrix$Get()
inverseMatrix <- cacheSolve(cacheMatrix)
inverseMatrix
inverseMatrix <- cacheSolve(cacheMatrix)
inverseMatrix
### OutPut from R ###
#cacheMatrix <- makeCacheMatrix(matrix(1:4,2,2,4))
#> cacheMatrix$Get()
#[,1] [,2]
#[1,] 1 2
#[2,] 3 4
#> inverseMatrix <- cacheSolve(cacheMatrix)
#> inverseMatrix
#[,1] [,2]
#[1,] -2.0 1.0
#[2,] 1.5 -0.5
#> inverseMatrix <- cacheSolve(cacheMatrix)
#Getting the cached value
#> inverseMatrix
#[,1] [,2]
#[1,] -2.0 1.0
#[2,] 1.5 -0.5