From 7050e9e83e7eec47f1e446a6ad2aeb8654996c6d Mon Sep 17 00:00:00 2001 From: silvie-sirova Date: Mon, 1 Dec 2025 17:17:10 +0100 Subject: [PATCH] Silvie Sirova - Programming Assignement 2 - solution --- cachematrix.R | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..f2952ed50db 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,42 @@ -## Put comments here that give an overall description of what your -## functions do +## These 2 functions enable to calculate matrix inversion and store it +## in cache. The purpose is to avoid repeating time consuming computation. +## example call: mx <- makeCacheMatrix(matrix(c(2,5,1,3),nrow=2,ncol=2)) +## cacheSolve(mx) -## Write a short comment describing this function -makeCacheMatrix <- function(x = matrix()) { +## makeCacheMatrix creates an object-list based on a matrix. +## It can be used for catching the inverse of that matrix. +## ! Assumption: x is always a square invertible matrix ! +makeCacheMatrix <- function(x = matrix()) { + #browser() + a <- NULL + set <- function(b = matrix()) { + x <<- b + a <<- x + } + get <- function() x + setinv <- function(solve) a <<- solve + getinv <- function() a + list(set = set, get = get, + setinv = setinv, + getinv = getinv) } - -## Write a short comment describing this function +## cacheSolve checks if the inverse of the matrix from makeCacheMatrix has +## already been computed. If so and the matrix not changed, it returns +## the inverse from cache, otherwise it computes the inverse of the matrix cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + #browser() + a <- x$getinv() + if(!is.null(a)) { + message("getting matrix inversion from cache") + return(a) + } + data <- x$get() + a <- solve(data) + x$setinv(a) + a } +