Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit eed409a

Browse files
committed
Homework 2 completed
This should be the final revision of homework 2.
1 parent 7f657dd commit eed409a

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

cachematrix.R

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,40 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## The Below functions demonstrate the principle of caching via lexical closure.
2+
## This can speed up program execution by avoiding recomputing values.
3+
## The functions below are modifications of the examples given for caching the
4+
## mean of a vector.
35

4-
## Write a short comment describing this function
56

6-
makeCacheMatrix <- function(x = matrix()) {
7+
## This function takes a matrix and returns a list containing:
8+
## "set" and "get" - functions to set and get the value of the matrix.
9+
## "setinverse" and "getinverse" - functions to comptute and retreive the inverse of the matrix
710

11+
makeCacheMatrix <- function(x = matrix()) {
12+
m <- NULL
13+
set <- function(y) {
14+
x <<- y
15+
m <<- NULL #defines m and sets it to NULL
16+
}
17+
get <- function() x
18+
setinverse <- function(inverse) m <<- inverse ## sets m to the value of "inverse" in the environment where m is defined
19+
getinverse <- function() m #returns m (as opposed to the uninverted x)
20+
list(set = set, get = get,
21+
setinverse = setinverse,
22+
getinverse = getinverse)
823
}
924

1025

11-
## Write a short comment describing this function
26+
## This as an extension of the R "solve" function to handle a list returned
27+
## by makeCacheMatrix
1228

1329
cacheSolve <- function(x, ...) {
1430
## Return a matrix that is the inverse of 'x'
31+
m <- x$getinverse()
32+
if(!is.null(m)) { #if m is defined
33+
message("getting cached data")
34+
return(m)
35+
}
36+
mat <- x$get() #otherwise
37+
m <- solve(mat, ...) #invert m
38+
x$setinverse(m) #and cache the value
39+
m #now return m
1540
}

0 commit comments

Comments
 (0)