Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. # testmatrix
  2. M <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE)
  3.  
  4. ###################Recursive####################
  5. potenzRec <- function(X, n = 2) {
  6.  
  7. # Checking if matrix can be multiplied
  8. if (!is.matrix(X) || nrow(X) != ncol(X)) {
  9. stop("X muss eine quadratische Matrix sein!")
  10. }
  11.  
  12. # non natural numbers lead to a stackoverflow error
  13. if (n != round(n) | n < 0) {
  14. stop("n muss eine natuerliche Zahl sein!")
  15. }
  16.  
  17. # identity matrix
  18. if (n == 0) {
  19. return(diag(1, nrow = nrow(X)))
  20. }
  21.  
  22. # returning matrix
  23. if (n == 1) {
  24. return(X)
  25. }
  26.  
  27. # recursion
  28. return(X %*% potenzRec(X, n-1))
  29. }
  30.  
  31.  
  32. M
  33. potenzRec(M, 2)
  34.  
  35.  
  36.  
  37. #################################### Funktion
  38. powerThing <- function(n = 2, M){
  39.  
  40. text1 <- "\nn muss eine nateurliche Zahl groesser gleich 0 sein!"
  41. text2 <- "\nM muss eine quadratische Matrix sein!"
  42.  
  43. # n muss eine natuerliche Zahl >= 0 sein
  44. if(!is.numeric(n) || n != round(n) | n < 0) {
  45. stop(text1)
  46. }
  47.  
  48. # M muss eine quadratische Matrix sein
  49. if(ncol(M) != nrow(M) || !(is.matrix(M))){
  50. stop(text2)
  51. }
  52.  
  53. # bei n = 0
  54. if(n == 0){
  55. return(diag(ncol(M)))
  56. }
  57.  
  58. if(n == 1) return(M)
  59. if(n == 2) return(M%*%M)
  60.  
  61. # bei n > 0
  62. if(n > 2){
  63. i <- 0
  64. while(i < n){
  65. res <- M %*% M
  66. i <- i + 1
  67. }
  68. }
  69. return(res)
  70. }
  71.  
  72. kappa <- powerThing(n = 3, M)
  73. kappa
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement