|
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 | +## This module provides inverse operations for a matrix, but |
| 2 | +## improves performance by caching intermediary results |
7 | 3 |
|
| 4 | +## This function creates a special "matrix" object that can cache its inverse, |
| 5 | +## using the supported functions attached to the matrix object. |
| 6 | +## |
| 7 | +## create matrix: amatrix = makeCacheMatrix(matrix(c(1,2,3,4), nrow=2, ncol=2)) |
| 8 | +## get matrix: amatrix$get() |
| 9 | +## set matrix: amatrix$set(matrix(c(0,5,99,66), nrow=2, ncol=2)) |
| 10 | +## inverse of matrix: amatrix$getinverse() |
| 11 | +makeCacheMatrix <- function(self.matrix = matrix()) { |
| 12 | + self.inv <- NULL |
| 13 | + set <- function(newmatrix) { |
| 14 | + self.matrix <<- newmatrix |
| 15 | + self.inv <<- NULL |
| 16 | + } |
| 17 | + get <- function() { |
| 18 | + self.matrix |
| 19 | + } |
| 20 | + getinverse <- function() { |
| 21 | + self.inv |
| 22 | + } |
| 23 | + setinverse <- function(inverse) { |
| 24 | + self.inv <<- inverse |
| 25 | + } |
| 26 | + list(set = set, get = get, |
| 27 | + setinverse = setinverse, |
| 28 | + getinverse = getinverse) |
8 | 29 | }
|
9 | 30 |
|
10 |
| - |
11 |
| -## Write a short comment describing this function |
12 |
| - |
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 31 | +## This function computes the inverse of the special "matrix" returned by |
| 32 | +## vmakeCacheMatrix above. If the inverse has already been calculated (and |
| 33 | +## the matrix has not changed), then cacheSolve retrieves the inverse from |
| 34 | +## the cache. |
| 35 | +cacheSolve <- function(cachematrx, ...) { |
| 36 | + inverse <- cachematrx$getinverse() |
| 37 | + if(!is.null(inverse)) { |
| 38 | + message("getting cached data") |
| 39 | + return(inverse) |
| 40 | + } |
| 41 | + data <- cachematrx$get() |
| 42 | + inverse <- solve(data, ...) |
| 43 | + cachematrx$setinverse(inverse) |
| 44 | + inverse |
15 | 45 | }
|
| 46 | + |
| 47 | +# mtrx = makeCacheMatrix(matrix(c(1,2,3,4), nrow=2, ncol=2)) |
| 48 | +# mtrx$get() |
| 49 | +# cacheSolve(mtrx) |
| 50 | +# mtrx$getinverse() |
| 51 | +# cacheSolve(mtrx) |
| 52 | +# mtrx$set(matrix(c(0,5,99,66), nrow=2, ncol=2)) |
| 53 | +# mtrx$get() |
| 54 | +# cacheSolve(mtrx) |
| 55 | +# mtrx$getinverse() |
| 56 | +# cacheSolve(mtrx) |
0 commit comments