Repository navigation
Expand file tree
/
Copy pathcachematrix.R
More file actions
70 lines (56 loc) · 2.06 KB
/
Copy pathcachematrix.R
File metadata and controls
70 lines (56 loc) · 2.06 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
## Put comments here that give an overall description of what your
## functions do
## makeCacheMatrix function simply creates a list of functions that
## operates on input data x. The list's functions are designed in such a
## way that when functions from the list are called the operations are
## made on objects in environments that is different from the calling
## environment due to operator '<<-'.
makeCacheMatrix <- function(x = matrix()) {
#upon calling the function we clear variable mInv containing inverse
#of matrix
mInv <- NULL
#define set function that sets data
set <- function(y) {
#as this function is called from other environment
#we use <<- operator
x <<- y
#new data means we need to clear mInv
mInv <<- NULL
}
#returns current data
get <- function() x
#upon computing a new inverse matrix in cacheSolve this inverse has
#to be set in the proper environment
setinverse <- function(inv) mInv <<- inv
#return currently stored matrix inverse - is null unless cacheSolve
#function is called first upon the object created by makeCacheMatrix
getinverse <- function() mInv
#return a new object containing list of functions to make
#a matrix object with caching functionality
list(set = set, get = get,
setinverse = setinverse, getinverse = getinverse)
}
## cacheSolve function is checking if the currently passed variable 'x'
## already contains cached version of the matrix inverse and if not it
## computes the matrix and caches it by using function from
## x's variable list
cacheSolve <- function(x) {
#get me current matrix inverse value'
mInv <- x$getinverse()
#if the returned value is non NULL object, we've already computed
#matrix inverse for this particular object
if (!is.null(mInv))
{
message("getting cached data")
return(mInv)
}
#else we store the data in local variable
data <- x$get()
#compute the matrix's inverse
mInv <- solve(data)
#and we set the inverse for the current object to be cached for
#possible future use
x$setinverse(mInv)
#return the computed matrix's inverse
mInv
}