Skip to content

Commit c419bb8

Browse files
committed
Assignment solution and example code
1 parent 7f657dd commit c419bb8

File tree

2 files changed

+59
-5
lines changed

2 files changed

+59
-5
lines changed

cachematrix.R

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,41 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
31

4-
## Write a short comment describing this function
2+
## This file is the solution to programming assignment 2 and contains 2 functions.
3+
4+
## Make a list of functions that work on a captured varible to store a matrix and a cached version of the inverse of the same matrix.
5+
## No computation in this funxtion, only getter & setter functions that work on the captured variable.
56

67
makeCacheMatrix <- function(x = matrix()) {
78

9+
## Store the cached inverse matrix "inside" this closure
10+
cache <- NULL
11+
12+
## Getter / setter functions to return
13+
get <- function() x
14+
getInverse <- function() cache
15+
setInverse <- function(m) cache <<- m
16+
17+
## return a list of functions, like the example code
18+
list(get = get, getInverse = getInverse, setInverse = setInverse)
819
}
920

1021

11-
## Write a short comment describing this function
22+
## Solve the inverse of a matrix, using the closue we created with makeCacheMatrix
23+
## If the cache is set return that. If not, solve() for matrix and return the result after setting the cache
1224

1325
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
26+
27+
inv <- x$getInverse() # # the varibale we will return after setting it to the correct matrix
28+
29+
if(is.null(inv)){
30+
# Nothing cached, solve and fill the cache
31+
matrix <- x$get()
32+
inv <- solve(matrix)
33+
x$setInverse(inv)
34+
} else {
35+
# Got cached result, nothing to do
36+
message("getting cached data")
37+
}
38+
39+
inv
40+
1541
}

example.R

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
## Use the example from the assignment
3+
4+
makeVector <- function(x = numeric()) {
5+
m <- NULL
6+
set <- function(y) {
7+
x <<- y
8+
m <<- NULL
9+
}
10+
get <- function() x
11+
setmean <- function(mean) m <<- mean
12+
getmean <- function() m
13+
list(set = set, get = get,
14+
setmean = setmean,
15+
getmean = getmean)
16+
}
17+
18+
cachemean <- function(x, ...) {
19+
m <- x$getmean()
20+
if(!is.null(m)) {
21+
message("getting cached data")
22+
return(m)
23+
}
24+
data <- x$get()
25+
m <- mean(data, ...)
26+
x$setmean(m)
27+
m
28+
}

0 commit comments

Comments
 (0)