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
73 lines (57 loc) · 2.34 KB
/
cachematrix.R
File metadata and controls
73 lines (57 loc) · 2.34 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
## The solution for the ProgrammingAssignment2 by A.Neverov
## This set of fulction allows to invert a square matrix
## and excludes the repeated calculations via the caching
## of the inverted matrix
### To use this function:
### 1) create the square matrix, for example m
### 2) create the CacheMatrix-object cm <- makeCacheMatrix(m)
### 3) calculate the inverted matrix im <- cacheSolve(cm)
### WARNING! It's impossible to invert non-square matrixes
### or matrixes containing NAs with these functions
## makeCacheMatrix - function creates a special object that
## contains the matrix and its invert
### Argument: x - the base square matrix
### Returns: the list contains method to access the matrix
### and its invert
### If x is non-square matrix or contains any NAs
### the function returns NULL
makeCacheMatrix <- function(x = matrix()) {
d <- dim(x)
if (d[1] == d[2] & !anyNA(x)) { #is it a square matrix without NAs
imtx <- NULL
set <- function(y) {
x <<- y
imtx <<- NULL
}
get <- function() x
setinvert <- function(...) imtx <<- solve(x, ...)
getinvert <- function() imtx
list( set = set, get = get, setinvert = setinvert, getinvert = getinvert)
} else {
message("The matrix must be square and must not have any NAs")
return(NULL)
}
}
## cacheSolve - the fucntion for inverting the square matrix
## created via the objects created with the makeCacheMatrix function
### Arguments: x - the makeCacheMatrix object
### ... - the set of arguments for solve() function
### Returns: if x isn't null the inverted matrix is returning
### if x is null the function returns NULL
cacheSolve <- function(x, ...) {
if (!is.null(x)) { #is the CacheMatrix not null
m <- x$getinvert()
if (!is.null(m)) {
message("getting cached data")
return(m)
} else {
x$set(m)
}
data <- x$get()
m <- x$setinvert(...)
m
} else {
message("The argument can not be NULL")
return(NULL)
}
}