|
1 |
| -# Create an object with new |
| 1 | +# Create a list object as to be able to calculate |
| 2 | +# Inverse Matrix using cache |
2 | 3 | makeCacheMatrix <- function(m = matrix())
|
3 | 4 | {
|
4 | 5 | inv <- NULL
|
5 | 6 |
|
| 7 | + # Set new matrix object and make cached inverse NULL |
6 | 8 | setMatrix <- function(new_m)
|
7 | 9 | {
|
8 | 10 | m <<- new_m
|
9 | 11 | inv <<- NULL
|
10 | 12 | }
|
11 | 13 |
|
| 14 | + # get matrix object |
12 | 15 | getMatrix <- function () m
|
13 | 16 |
|
| 17 | + # Set Inverse matrix to a global variable as to use |
| 18 | + # it for inverse cache |
14 | 19 | setInverse <- function(new_inv) inv <<- new_inv
|
15 |
| - getInverse <- function()a < inv |
16 | 20 |
|
| 21 | + # get cached Inversed Matrix |
| 22 | + getInverse <- function() inv |
| 23 | + |
| 24 | + # return list with function |
17 | 25 | list(setMatrix = setMatrix,
|
18 | 26 | getMatrix = getMatrix,
|
19 | 27 | setInverse = setInverse,
|
20 | 28 | getInverse = getInverse)
|
21 | 29 | }
|
22 | 30 |
|
| 31 | +# This function should take as argument a list that be created |
| 32 | +# using makeCacheMatrix |
23 | 33 | cacheSolve <- function(m, ...)
|
24 | 34 | {
|
25 |
| - ## Return a matrix that is the inverse of 'x' |
| 35 | + # First take cached Inversed Matrix |
26 | 36 | inv <- m$getInverse()
|
| 37 | + |
| 38 | + # if the cached Inversed matrix is not NULL then return it |
| 39 | + # and take advantage from cache |
27 | 40 | if(!is.null(inv))
|
28 | 41 | {
|
29 | 42 | message("*** Inverse Matrix is from cache ***")
|
30 | 43 | return(inv)
|
31 | 44 | }
|
| 45 | + |
| 46 | + # otherwise get matrix |
32 | 47 | temp_matrix <- m$getMatrix()
|
| 48 | + |
| 49 | + # calculate inverse matrix |
33 | 50 | inv <- solve(temp_matrix)
|
| 51 | + |
| 52 | + # put new calculated inversed matrix to cache |
| 53 | + # for future use if call this function again |
| 54 | + # and matrix do not cache |
34 | 55 | m$setInverse(inv)
|
35 | 56 | inv
|
36 | 57 | }
|
0 commit comments