forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
51 lines (45 loc) · 1.48 KB
/
cachematrix.R
File metadata and controls
51 lines (45 loc) · 1.48 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
## The Project is the second programming assignment on course
## R Programming started on May, 2014.
##
## The aim is to cache heavy matrix calculations using scoping
## rules of R
## Example of use:
## > x <- matrix(c(1,2,3,4),nrow=2,ncol=2)
## > xcache <- makeCacheMatrix(x)
## > y <- cacheSolve(xcache)
## > y <- cacheSolve(xcache)
## getting cached inverse
## > x %*% y ## must return identity matrix..
## [,1] [,2]
## [1,] 1 0
## [2,] 0 1
## .. so it is!
## This function creates a list with cachable matrix object and
## methods to manipulate this object
makeCacheMatrix <- function(x = matrix()) {
m <- NULL ## This is a cached value
set <- function(y) { ## The function to set new value to cachable matrix
x <<- y
m <<- NULL
}
get <- function() x # Getter method
setinverse <- function(minv) m <<- minv ## Setting inverse cache
getinverse <- function() m ## Gettinge cached inverse
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse) ## Creating an object with getters and setters
}
## The function returns cached inverse matrix if it exists
## and calculates it vice versa
cacheSolve <- function(x, ...) {
m <- x$getinverse()
if (!is.null(m)) { ## if there is a chached value...
message("getting cached inverse")
return(m) ## ..return it
} ## ..otherwise get data, calculate inverse and cache
data <- x$get()
m <- solve(data,...)
x$setinverse(m)
## Return a matrix that is the inverse of 'x'
m
}