forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraded.R
More file actions
45 lines (37 loc) · 1.88 KB
/
graded.R
File metadata and controls
45 lines (37 loc) · 1.88 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
makeCacheMatrix <- function(x = numeric()) {
i<-NULL
set<-function(y) { x<<-y #sets the matrix value which future input to cacheSolve will be compared against
}
get<-function() x # returns the matrix when called
setinverse<-function(inverse) i<<-inverse # stores the matrix inverse provided as its input
getinverse<-function() i #returns the inverse when called
invisible(list(set=set, get= get, setinverse= setinverse, getinverse = getinverse)) #creates a list of the four functions
}
a<<-makeCacheMatrix() #allows for the four functions within makeCacheMatrix to be called more conveniently.
#For example, a$set()..
## function designed to calculate the inverse of an inputted matrix. If the matrix has not changed, then the
##function returns the cache'd inverse of the matrix rather than computing it again
cacheSolve <- function(x, ...) {
f<-a$get() #return the matrix value stored in makeCacheMatrix
i<-a$getinverse() # Return the inverse matrix stored in makeCacheMatrix
if(is.null(i)) { #if the function has not been called before, and therefore does not have a matrix value stored,
# compute and store a matrix
i<-solve(x) # compute the inverse of matrix x
a$setinverse(i) # store this value in makeCacheMatrix
a$set(x)
i
}
else if(identical(x, f)) { ##if the value of the last matrix "f" equals the new matrix input to cacheSolve "x",
# then return the cached inverse
print("getting cached data")
i
}
else { # if the matrix "x" is different to that currently stored in makeCacheMatrix,
#then calculate a new inverse for the matrix and store the inverse in makeCacheMatrix
i<-solve(x)
a$setinverse(i)
a$set(x)
i
## Return a matrix that is the inverse of 'x'
}
}