|
1 | | -## Put comments here that give an overall description of what your |
2 | | -## functions do |
| 1 | +## This programme and its functions are used to calculate the inverse of a matrix |
| 2 | +#and cache it in memory. For complex and iterative programs, if there is no change |
| 3 | +#to the values being calculated in the current iteration, we can optimise our |
| 4 | +#code by first checking whether a similar calculation has already been performed, |
| 5 | +#and if so, simply recall that calculation's result. |
3 | 6 |
|
4 | | -## Write a short comment describing this function |
| 7 | +## This function is used to create a list of 4 inner functions: |
| 8 | +#get, set, getinv and setinv. |
| 9 | +#Get and set are used to obtain or set the value of the matrix |
| 10 | +#getinv and setinv are used to obtain and recall the inverse of the matrix |
5 | 11 |
|
6 | 12 | makeCacheMatrix <- function(x = matrix()) { |
| 13 | + mat<- NULL |
| 14 | + set <- function (y){ |
| 15 | + x<<-y |
| 16 | + mat<<-NULL |
| 17 | + } |
| 18 | + get <- function() x |
| 19 | + setinv <- function(inv) mat <<- inv |
| 20 | + getinv <- function() mat |
| 21 | + list(set=set, get=get, setinv=setinv, getinv=getinv) |
7 | 22 |
|
8 | 23 | } |
9 | 24 |
|
10 | 25 |
|
11 | | -## Write a short comment describing this function |
| 26 | +## This function calculates the inverse of the matrix and stores it in the cache. |
12 | 27 |
|
13 | 28 | cacheSolve <- function(x, ...) { |
14 | | - ## Return a matrix that is the inverse of 'x' |
| 29 | + mat<-x$getinv() |
| 30 | + if (!is.null(mat)){ |
| 31 | + message("Getting the cached data") |
| 32 | + return (mat) |
| 33 | + } |
| 34 | + data <- x$get(); |
| 35 | + mat <- solve(data, ...) |
| 36 | + x$setinv(mat) |
| 37 | + mat |
15 | 38 | } |
0 commit comments