forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
41 lines (36 loc) · 1.57 KB
/
cachematrix.R
File metadata and controls
41 lines (36 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
## The two functions makeCacheMatrix and cacheSolve work together to cache the inverse of a matrix, thereby avoiding unnecessary repeated calculations. makeCacheMatrix creates a special list object that stores a matrix and can also store its inverse. cacheSolve retrieves the cached inverse if it has already been calculated; otherwise, it calculates the inverse, stores it in the cache, and returns it.
## The makeCacheMatrix function creates a special list object that stores a matrix and also contains a cache for its inverse. The structure is based on the example from the exercise in which the mean value of a vector was temporarily stored. This principle has been applied to matrices here.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL # Cache für die Inverse
set <- function(y) {
x <<- y # neue Matrix setzen
inv <<- NULL # Cache resetten, weil Matrix sich geändert hat
}
get <- function() {
x
}
setinv <- function(inverse) {
inv <<- inverse
}
getinv <- function() {
inv
}
list(
set = set,
get = get,
setinv = setinv,
getinv = getinv
)
}
## The cacheSolve function computes the inverse of the matrix stored inside a makeCacheMatrix object. It first checks whether the inverse is already available in the cache. If so, it returns the cached value immediately to avoid redundant computation.
cacheSolve <- function(x, ...) {
inv <- x$getinv()
if (!is.null(inv)) {
message("getting cached data")
return(inv)
}
mat <- x$get()
inv <- solve(mat, ...) # Inverse berechnen
x$setinv(inv)
inv
}