|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
| 1 | +## Date: 19 January 2015 |
| 2 | +## Course: R Programming |
| 3 | +## |
| 4 | +## Testing procedures |
| 5 | +## Step 1: q <- makeCacheMatrix() |
| 6 | +## Step 2: q$set(matrix(1:9,3,3)) |
| 7 | +## Step 3: cacheSolve(q) |
| 8 | +## This returns the inverse of the matrix and caches it. |
| 9 | +## Step 4: cacheSolve(q) |
| 10 | +## This returns the cached solution with a message 'Getting cached data!' |
| 11 | +## |
| 12 | +## makeCacheMatrix function description |
| 13 | +## |
| 14 | +## makeCacheMatrix is a function that creates a 'matrix' object |
| 15 | +## that can cache its inverse. Solving is not handled here. |
| 16 | +## makeCacheMatrix saves the matrix to variable x and its inverse |
| 17 | +## to m. The returned list contains: |
| 18 | +## set: sets matrix & resets cache of inverse |
| 19 | +## get: returns matrix |
| 20 | +## setsolution: saves solve value |
| 21 | +## getsolution: returns cached inverse value |
5 | 22 |
|
6 | 23 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 24 | + m <- NULL |
| 25 | + set <- function (y) { |
| 26 | + x <<- y |
| 27 | + m <<- NULL |
| 28 | + } |
| 29 | + get <- function() x |
| 30 | + setsolution <- function(solve) m <<- solve |
| 31 | + getsolution <- function() m |
| 32 | + list(set = set, get = get, |
| 33 | + setsolution = setsolution, getsolution = getsolution |
| 34 | + ) |
8 | 35 | }
|
| 36 | +## cacheSolve function description |
| 37 | +## |
| 38 | +## cacheSolve is a function to get inversed matrix from |
| 39 | +## the object created by the previous function. It takes |
| 40 | +## the object as argument x, and checks if the inverse value is |
| 41 | +## already cached. If cached, it returns the cached value. If |
| 42 | +## not cached, it calculates the inverse for the matrix in x |
| 43 | +## and saves into the x cache using setsolution. The result |
| 44 | +## is then returned. |
9 | 45 |
|
10 |
| - |
11 |
| -## Write a short comment describing this function |
12 |
| - |
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 46 | +cacheSolve <- function(x=matrix(), ...) { |
| 47 | + m<-x$getsolution() |
| 48 | + if(!is.null(m)) { |
| 49 | + message("Getting cached data!") |
| 50 | + return(m) |
| 51 | + } |
| 52 | + matrix <- x$get() |
| 53 | + m <- solve(matrix, ...) |
| 54 | + x$setsolution(m) |
| 55 | + m |
15 | 56 | }
|
0 commit comments