From 4682325581403edc997596d82d480d4607ad99b8 Mon Sep 17 00:00:00 2001 From: AgnesBondeson861 Date: Wed, 3 Sep 2025 15:37:29 +0200 Subject: [PATCH 1/2] Update cachematrix.R --- cachematrix.R | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa4..67083405db 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,30 @@ -## Put comments here that give an overall description of what your -## functions do -## Write a short comment describing this function +## This function creates a matrix object that can cache its inverse 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 - +#This function computes the inverse of the matrix, +#if it has not been computed before or +#retrieves the answer that has been already calculated cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + m <- x$getinverse() + if(!is.null(m)) { + message("getting cached inverse") + return(m) + } + data <- x$get() + m <- solve(data, ...) + x$setinverse(m) + m } From f23e393348532e23a8dbd104717b6f4d22072b18 Mon Sep 17 00:00:00 2001 From: AgnesBondeson861 Date: Thu, 4 Sep 2025 12:32:15 +0200 Subject: [PATCH 2/2] Update cachematrix.R --- cachematrix.R | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index 67083405db..e0c02eb366 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,30 +1,34 @@ + ## This function creates a matrix object that can cache its inverse makeCacheMatrix <- function(x = matrix()) { m <- NULL - set <- function(y) { + set <- function(y) { # sets the variables x and y x <<- y m <<- NULL } - get <- function() x - setinverse <- function(inverse) m <<- inverse - getinverse <- function() m + get <- function() x #gets x + setInverse <- function(inverse) m <<- inverse #sets the inverse to m + getInverse <- function() m #gets m list(set = set, get = get, - setinverse = setinverse, - getinverse = getinverse) + setInverse = setInverse, + getInverse = getInverse) } #This function computes the inverse of the matrix, #if it has not been computed before or #retrieves the answer that has been already calculated cacheSolve <- function(x, ...) { - m <- x$getinverse() - if(!is.null(m)) { + m <- x$getInverse()#get inverse or NULL if it has not been computed before + + if(!is.null(m)) {# if the inverse has been computed before, return that inverse message("getting cached inverse") return(m) } data <- x$get() - m <- solve(data, ...) - x$setinverse(m) + m <- solve(data, ...)#compute inverse if it has not been computed before + x$setInverse(m) m } + +