From 7a1205b9f86c31742cb59ebda16e0162ceb343a7 Mon Sep 17 00:00:00 2001 From: Andy Pliszka Date: Sun, 27 Jul 2014 16:26:02 -0400 Subject: [PATCH] Implements makeCacheMatrix and cacheSolve --- cachematrix.R | 38 +++++++++++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..245a90b7fb4 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,39 @@ -## Put comments here that give an overall description of what your -## functions do +## makeCacheMetrix and cacheSolve are functions for matrix inverse calculation +## with caching of results. Matrix inverse calculations are slow for large matrixes. +## Caching the results improves the performance of the calculation. Caching improves +## performance if you are calculating matrix inverse for the same matrix multiple times. -## Write a short comment describing this function +## makeCacheMatrix creates a matrix container list. The created list contains +## get and set functions for storing and retrieving of the matrix. getinverse and setinverse +## functions get or set the matrix inverse cached value. makeCacheMatrix <- function(x = matrix()) { - + m <- NULL + set <- function(y) { + x <<- y + m <<- NULL + } + get <- function() x + setinverse <- function(inverse) m <<- inverse + getinverse <- function() m + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } - -## Write a short comment describing this function +## cacheSolve calculates matrix inverse of the x matrix. This function +## first checks if there is a cached inverse. If there is a cached inverse then +## cacheSolve returns the cached value immediately. If there is no cached inverse +## it computes the inverse first, stores it in the cache, and returns the inverse value. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + m <- x$getinverse() + if(!is.null(m)) { + message("getting cached data") + return(m) + } + data <- x$get() + m <- solve(data, ...) + x$setinverse(m) + m }