Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # testmatrix
- M <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE)
- ###################Recursive####################
- potenzRec <- function(X, n = 2) {
- # Checking if matrix can be multiplied
- if (!is.matrix(X) || nrow(X) != ncol(X)) {
- stop("X muss eine quadratische Matrix sein!")
- }
- # non natural numbers lead to a stackoverflow error
- if (n != round(n) | n < 0) {
- stop("n muss eine natuerliche Zahl sein!")
- }
- # identity matrix
- if (n == 0) {
- return(diag(1, nrow = nrow(X)))
- }
- # returning matrix
- if (n == 1) {
- return(X)
- }
- # recursion
- return(X %*% potenzRec(X, n-1))
- }
- M
- potenzRec(M, 2)
- #################################### Funktion
- powerThing <- function(n = 2, M){
- text1 <- "\nn muss eine nateurliche Zahl groesser gleich 0 sein!"
- text2 <- "\nM muss eine quadratische Matrix sein!"
- # n muss eine natuerliche Zahl >= 0 sein
- if(!is.numeric(n) || n != round(n) | n < 0) {
- stop(text1)
- }
- # M muss eine quadratische Matrix sein
- if(ncol(M) != nrow(M) || !(is.matrix(M))){
- stop(text2)
- }
- # bei n = 0
- if(n == 0){
- return(diag(ncol(M)))
- }
- if(n == 1) return(M)
- if(n == 2) return(M%*%M)
- # bei n > 0
- if(n > 2){
- i <- 0
- while(i < n){
- res <- M %*% M
- i <- i + 1
- }
- }
- return(res)
- }
- kappa <- powerThing(n = 3, M)
- kappa
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement