|
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 | +## Writing two functions that cache the inverse of a matrix |
7 | 2 |
|
| 3 | +## This function creates a special "matrix" object that can cache its inverse |
| 4 | +makeCacheMatrix <- function( m = matrix() ) { |
| 5 | +## Initializing the inverse property |
| 6 | +i <- NULL |
| 7 | +## Setting the matrix method |
| 8 | +set <- function( matrix ) { |
| 9 | +m <<- matrix |
| 10 | +i <<- NULL |
| 11 | +} |
| 12 | +## Getting the matrix method |
| 13 | +get <- function() { |
| 14 | +## Returning the matrix |
| 15 | +m |
| 16 | +} |
| 17 | +## Setting the inverse of the matrix |
| 18 | +setInverse <- function(inverse) { |
| 19 | +i <<- inverse |
| 20 | +} |
| 21 | +## Getting the inverse of the matrix |
| 22 | +getInverse <- function() { |
| 23 | +## Returning the inverse property |
| 24 | +i |
| 25 | +} |
| 26 | +## Returning a list of methods |
| 27 | +list(set = set, get = get, |
| 28 | +setInverse = setInverse, |
| 29 | +getInverse = getInverse) |
8 | 30 | }
|
9 | 31 |
|
10 |
| - |
11 |
| -## Write a short comment describing this function |
| 32 | +## This function computes the inverse of the special "matrix" |
| 33 | +## returned by makeCacheMatrix above. If the inverse has already |
| 34 | +## been calculated (and the matrix has not changed), then the cachesolve |
| 35 | +## should retrieve the inverse from the cache. |
12 | 36 |
|
13 | 37 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 38 | +## Returning matrix that is the inverse of 'x' |
| 39 | +m <- x$getInverse() |
| 40 | +## Returning the inverse if its set already |
| 41 | +if( !is.null(m) ) { |
| 42 | +message("getting cached data") |
| 43 | +return(m) |
| 44 | +} |
| 45 | +## Getting the matrix from the object |
| 46 | +data <- x$get() |
| 47 | +## Calculating the inverse by using matrix multiplication |
| 48 | +m <- solve(data) %*% data |
| 49 | +## Setting the inverse to the object |
| 50 | +x$setInverse(m) |
| 51 | +## Finally returning the matrix |
| 52 | +m |
15 | 53 | }
|
0 commit comments