From 39e93bfb31cd99d580820aac3ec8848621eadd6f Mon Sep 17 00:00:00 2001 From: David Escanuela Date: Tue, 22 Apr 2014 09:44:57 +0200 Subject: [PATCH] Solution Solution --- cachematrix.R | 47 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..11763274364 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,46 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function - -makeCacheMatrix <- function(x = matrix()) { +## Matrix inversion is usually a costly computation and their may be some benefit to caching +## the inverse of a matrix rather than compute it repeatedly. +## makeCacheMatrix: This function creates a special "matrix" object that can cache its inverse. +makeCacheMatrix <- function(x = matrix()) +{ + s <- NULL + #set the value of the vector + set <- function(y) + { + x <<- y + s <<- NULL + } + #get the value of the vector + get <- function() x + #set the value of the mean + setsolve <- function(solve) s <<- solve + #get the value of the mean + getsolve <- function() s + list(set = set, get = get, setsolve = setsolve, getsolve = getsolve) } -## Write a short comment describing this function +## cacheSolve: This function computes the inverse of the special "matrix" returned by makeCacheMatrix +## above. If the inverse has already been calculated (and the matrix has not changed), then the +## cachesolve should retrieve the inverse from the cache. -cacheSolve <- function(x, ...) { +cacheSolve <- function(x, ...) +{ ## Return a matrix that is the inverse of 'x' + #get the value of the mean + s <- x$getsolve() + if(!is.null(s)) + { + message("Getting cached data") + #If exists return the inverse of the special "matrix" + return(s) + } + #get the value of the vector + data <- x$get() + #calculate the inverse of the special "matrix" + s <- solve(data, ...) + #set the value of the mean + x$setsolve(s) + s }