|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## Functions for operating on matrix objects |
| 2 | +## with caching capability for inverse value |
| 3 | +## |
| 4 | +## made for programming assignment 2, |
| 5 | +## R programming course, 20.12.2014 |
3 | 6 |
|
4 |
| -## Write a short comment describing this function |
| 7 | +## Function to create our matrix object |
5 | 8 |
|
6 | 9 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 10 | + inv <- NULL |
| 11 | + # Set the matrix |
| 12 | + set <- function(y) { |
| 13 | + x <<- y |
| 14 | + inv <<- NULL |
| 15 | + } |
| 16 | + # Get the matrix |
| 17 | + get <- function() x |
| 18 | + # Set inverse matrix value |
| 19 | + setinv <- function(minv) inv <<- minv |
| 20 | + # Get inverse matrix value |
| 21 | + getinv <- function() inv |
| 22 | + # Return CacheMatrix object |
| 23 | + list(set=set, get=get, setinv=setinv, getinv=getinv) |
8 | 24 | }
|
9 | 25 |
|
10 | 26 |
|
11 |
| -## Write a short comment describing this function |
| 27 | +## Function to request inverse value. Retrieved value can be |
| 28 | +## either precached or calculated on-the-fly |
12 | 29 |
|
13 | 30 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 31 | + # Return a matrix that is the inverse of 'x' |
| 32 | + inv <- x$getinv() |
| 33 | + # Check if the value already calculated |
| 34 | + if(!is.null(inv)) { |
| 35 | + message("getting cached value") |
| 36 | + return(inv) |
| 37 | + } |
| 38 | + # Get the matrix |
| 39 | + data <- x$get() |
| 40 | + # Solve the matrix |
| 41 | + inv <- solve(data, ...) |
| 42 | + # Set the cache |
| 43 | + x$setinv(inv) |
| 44 | + # Return calculated value |
| 45 | + inv |
15 | 46 | }
|
0 commit comments