From c8fdea71cf57550edcd98da5dc4cbf69a114dbac Mon Sep 17 00:00:00 2001 From: Caro Borre Date: Wed, 27 Apr 2022 20:24:13 +0200 Subject: [PATCH] cachematrix.R --- .Rhistory | 0 cachematrix.R | 46 +++++++++++++++++++++++++++++++++++++++------- 2 files changed, 39 insertions(+), 7 deletions(-) create mode 100644 .Rhistory diff --git a/.Rhistory b/.Rhistory new file mode 100644 index 00000000000..e69de29bb2d diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..dcb39d1be2b 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,47 @@ -## Put comments here that give an overall description of what your -## functions do +#Second programming assignment: -## Write a short comment describing this function +#*makeCacheMatrix:* This function creates a special "matrix" object that can +# cache its inverse. -makeCacheMatrix <- function(x = matrix()) { +#*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 `cacheSolve` should retrieve +# the inverse from the cache. -} +makeCacheMatrix <- function(x = matrix()) { + + i <- NULL #where the inverse is to be stored + set <- function(y) { + x <<- y #The <<- operator is necessary to enclose the enviroment of the parent function + i <<- NULL + } + + get <- function() x #Anonymus functions to set and get a matrix and cahce its inverse + setinverse <- function(inverse) i <<- inverse + getinverse <- function() i + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) +} -## Write a short comment describing this function +# Now, we are interested in calculating the inverse of the matrix object generated +#by the parent function makeCacheMatrix. +#If the inverse is created (!is.null) then cacheSolve will retrieve it, otherwise +#it will calculate it. + cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + + i <- x$getinverse() + if (!is.null(i)) { + message("getting cached data") + return(i) + } + + data <- x$get() + i <- solve(data, ...) + x$setinverse(i) + i + }