forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Submission
54 lines (48 loc) · 2.53 KB
/
Submission
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
#This fucntion creates a matrix and a list detailing the operations performed on that matrix
makeMat <- function(x = matrix(1:4,2)) {
#This function requieres a square matrix, x, as input (Solve function will not work unless matrix is square)
#The output if this function is a list, which details the matrix, the operation to do with it (solve), the
#result of the operation (matrix inverse), and a variable stating if the operation has already been performed (i)
#It first sets i (the inverse of x) as null
i <- NULL
#set will store y as x, and i as null
#this condition is used to check if the inverse has allready been calculated in cacheSolve.R
set <- function(y) {
x <<- y
i <<- NULL
}
#get stores the matrix
get <- function() x
#setsolve defines the solve operation
setsolve <- function(solve) i <<- solve
#getsolve is the inverse of x
getsolve <- function() i
#Finally all the 4 objects are stored in a list, named x
list(set = set, get = get,
setsolve = setsolve,
getsolve = getsolve)
}
##----------------------------------------------------------------------------------------------------------------------------##
##----------------------------------------------------------------------------------------------------------------------------##
#this function will check if the inverse has allready been calculated for a given matrix, if so, then it returns the cached result
#otherwise it will calculate it.
cachesolve <- function(x, ...) {
#cachesolve will use the output list generated by makeCacheMatrix.R, this list has a sqaure matrix, its inverse
#the operation used to get the inverse (solve), and a variable describing if the operation has allready been
#performed, i which is null if it has.
i <- x$getsolve()
#gets the solve status (either null, if it hasnt been inversed or the inverse, if it has)
if(!is.null(i)) {
#if i is null, then the inverse has been calculated and cached data is obtained
message("getting cached data")
#terminates the function
return(i)
}
#if has been solved, it gets the matrix in "data"
data <- x$get()
#inverses it
i <- solve(data, ...)
#makes getsolve the inverse so that next time the inverse is not calculated but obtained from cache
x$setsolve(i)
i
}