|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +############################################################################## |
| 2 | +## |
| 3 | +## KT |
| 4 | +## Programming assignment 2 |
| 5 | +## R Programming Course (Coursera, April 2014) |
| 6 | +## |
| 7 | +## Contains a function that creates a special "matrix" that can cache its inverse |
| 8 | +## And a second function that calculates or retrieves (depending on whether it |
| 9 | +## exists already) the inverse of said "special matrix and returns that inverse |
| 10 | +## |
| 11 | +############################################################################## |
3 | 12 |
|
4 |
| -## Write a short comment describing this function |
5 | 13 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
7 | 14 |
|
| 15 | +## makeCacheMatrix creates a list that contains functions to: |
| 16 | +## 1. set the value of a matrix |
| 17 | +## 2. get the value of a matrix |
| 18 | +## 3. set the value of an invserse of a matrix |
| 19 | +## 4. get the value of an invserse of a matrix |
| 20 | + |
| 21 | +makeCacheMatrix <- function(x = matrix()) { |
| 22 | + m <- NULL |
| 23 | + set <- function(y) { |
| 24 | + x <<- y #set matrix equal to matrix value |
| 25 | + m <<- NULL #set inverse to NULL |
| 26 | + } |
| 27 | + get <- function() x ## return matrix |
| 28 | + setinverse <- function(inverse) m <<- inverse #set inverse of matrix |
| 29 | + getinverse <- function() m #return the inverse of matrix |
| 30 | + |
| 31 | + #return list with functions 1-4 as listed above in large comment |
| 32 | + list(set = set, |
| 33 | + get = get, |
| 34 | + setinverse = setinverse, |
| 35 | + getinverse = getinverse) |
8 | 36 | }
|
9 | 37 |
|
10 | 38 |
|
11 |
| -## Write a short comment describing this function |
| 39 | + |
| 40 | + |
| 41 | +## cacheSolve returns the inverse of an invertable matrix. |
| 42 | +## First, it checks if the inverse of the matrix has already been calculated |
| 43 | +## If so, it "gets" this inverse and returns it. Otherwise, it calculates the |
| 44 | +## inverse, sets the value of the inverted matrix using the 'setinverse' |
| 45 | +## function, and returns the inverse |
12 | 46 |
|
13 | 47 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 48 | + m <- x$getinverse() #check if matrix inverse has already been calculated |
| 49 | + if(!is.null(m)) { # if inverse is already calculated |
| 50 | + message("fetching cached data") |
| 51 | + return(m) # return inverse and exit function |
| 52 | + } |
| 53 | + data <- x$get() # if matrix inverse hasn't been calculated, get matrix |
| 54 | + m <- solve(data, ...) # solve the inverse |
| 55 | + x$setinverse(m) # set the inverse |
| 56 | + m # return the inverse and exit function |
15 | 57 | }
|
0 commit comments