Skip to content

Commit 0cdaf01

Browse files
committed
cache matrix implementation
1 parent 7f657dd commit 0cdaf01

File tree

2 files changed

+58
-10
lines changed

2 files changed

+58
-10
lines changed

cachematrix.R

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,47 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
5-
6-
makeCacheMatrix <- function(x = matrix()) {
1+
## Note: names of the methods changed to follow guidlines suggested here:
2+
## https://google-styleguide.googlecode.com/svn/trunk/Rguide.xml#identifiers
73

4+
## factory function to create a matrix that can cache the value of its inverse
5+
MakeCacheMatrix <- function(x = matrix()) {
6+
# initialize the cached value of matrix inverse to be NULL
7+
inverse.cache <- NULL
8+
9+
# create setter function to...
10+
Set <- function(y) {
11+
# ...store the matrix
12+
x <<- y
13+
# ...and reset the cached inverse value
14+
inverse.cache <<- NULL
15+
}
16+
17+
# create getter function - return incapsulated matrix
18+
Get <- function() x
19+
20+
SetInverse <- function(inverse) inverse.cache <<- inverse
21+
22+
GetInverse <- function() inverse.cache
23+
24+
list(Set = Set, Get = Get,
25+
SetInverse = SetInverse,
26+
GetInverse = GetInverse)
827
}
928

1029

11-
## Write a short comment describing this function
12-
13-
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
30+
## Calculate the inverse of the matrix; get the cached inverse matrix if it exists
31+
CacheSolve <- function(x, ...) {
32+
# get cached inverse
33+
inverse <- x$GetInverse()
34+
# ...return cached inverse if it exists
35+
if(!is.null(inverse)) {
36+
message("getting cached data")
37+
return(inverse)
38+
}
39+
# otherwise get the matrix
40+
data <- x$Get()
41+
# ...calculate inverse
42+
inverse <- solve(data, ...)
43+
# ...and cache it
44+
x$SetInverse(inverse)
45+
# return calculated inverse matrix object
46+
inverse
1547
}

cachematrix.test.R

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
source('cachematrix.R')
2+
3+
# create square invertable marix
4+
m=rbind(c(1, -1/4), c(-1/4, 1))
5+
6+
# create cached matrix
7+
cache.m <- MakeCacheMatrix(c)
8+
9+
# caclulate inverse
10+
inv <- CacheSolve(cc)
11+
12+
#print result
13+
inv
14+
15+
# check the result of multiplication of inverse by original - expect identity matri
16+
inv %*% m

0 commit comments

Comments
 (0)