This repository was archived by the owner on Jul 12, 2021. It is now read-only.
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
45 lines (35 loc) · 1.28 KB
/
cachematrix.R
File metadata and controls
45 lines (35 loc) · 1.28 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
# R Programming - Assignment 2 - Lexical Scoping
# makeCacheMatrix store the matrix and the inverse
# cacheSolve uses the solve function to inverse a matrix and store a copy so it doesn't need to be recalculated
## makeCacheMatrix -creates a special "matrix" object that can cache it's inverse
makeCacheMatrix <- function(x = matrix()) {
inverse <- NULL
# Set a new matrix, and null the inverse so that it will be recalculated the next time cacheSolve is called
set <- function(y) {
x <<- y
inverse <<- NULL
}
get <- function() x
setinverse <- function(new_inverse) inverse <<- new_inverse
getinverse <- function() inverse
list( set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## cacheSolve -compute the inverse of the special "matrix"
## if the cache has already been calculated, and the matrix hasn't changed
## the cache is returned
## otherwise calculate, cache and return the matrix
cacheSolve <- function(x, ...)
{
inverse <- x$getinverse()
if(!is.null(inverse))
{
message("getting cached data")
return(inverse)
}
data <- x$get()
inverse <- solve(data)
x$setinverse(inverse)
inverse
}