Skip to content

Commit 74e9d3a

Browse files
committed
initial version
1 parent 7f657dd commit 74e9d3a

File tree

1 file changed

+43
-8
lines changed

1 file changed

+43
-8
lines changed

cachematrix.R

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,50 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
1+
## Coursera "R Programming", Assignment 2.
2+
##
3+
## Author: Edward Garson
4+
## Date: December 2014
5+
##
6+
## https://class.coursera.org/rprog-016/human_grading/view/courses/972581/assessments/3/submissions
57

8+
## Return a list object that encapsulates a given matrix and its calculated inverse.
9+
## `x_inv' is the memoized variable that caches the inverse
10+
## `inverse' is an accessor function for the inverse of the given matrix (`x_inv')
11+
## `cache' is a function to set the value of `x_inv', and conveniently returns it
612
makeCacheMatrix <- function(x = matrix()) {
7-
13+
x_inv <- NULL
14+
inverse <- function() x_inv
15+
cache <- function(inv) { x_inv <<- inv; x_inv }
16+
list(matrix = x, inverse = inverse, cache = cache)
817
}
918

19+
## Returns the inverse of `x$matrix', potentially retrieving it from cache
20+
cacheSolve <- function(x, ...) {
21+
if (!is.null(x$inverse())) {
22+
# message("cache hit")
23+
return(x$inverse())
24+
}
25+
x$cache(solve(x$matrix, ...)) # n.b. this *returns* the inverse in addition to caching it
26+
}
1027

11-
## Write a short comment describing this function
28+
makeVector <- function(x = numeric()) {
29+
m <- NULL
30+
set <- function(y) {
31+
x <<- y
32+
m <<- NULL
33+
}
34+
get <- function() x
35+
setmean <- function(mean) m <<- mean
36+
getmean <- function() m
37+
list(set = set, get = get, setmean = setmean, getmean = getmean)
38+
}
1239

13-
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
40+
cachemean <- function(x, ...) {
41+
m <- x$getmean()
42+
if(!is.null(m)) {
43+
message("getting cached data")
44+
return(m)
45+
}
46+
data <- x$get()
47+
m <- mean(data, ...)
48+
x$setmean(m)
49+
m
1550
}

0 commit comments

Comments
 (0)