Für Vorlesungen, bitte die Webseite verwenden. https://flavigny.de/lecture
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
961B

  1. n_diag <- function(mat, n) {
  2. stopifnot("Matrix not quadratic" = nrow(mat) == ncol(mat))
  3. stopifnot("Matrix does not have such a (sub)diagonal" = abs(n) < nrow(mat))
  4. dg <- c()
  5. for (i in (1:(nrow(mat)-abs(n)))) {
  6. elem <- if (n > 0) {
  7. mat[i, i+n]
  8. } else {
  9. mat[i+abs(n), i]
  10. }
  11. dg <- c(dg, elem)
  12. }
  13. return(dg)
  14. }
  15. `n_diag<-` <- function(x, value, n) {
  16. stopifnot("Matrix not quadratic" = nrow(mat) == ncol(mat))
  17. stopifnot("Matrix does not have such a (sub)diagonal" = abs(n) < nrow(mat))
  18. stopifnot("Subdiagonal length and replacement do not match" = length(value) == nrow(mat) - abs(n))
  19. for (i in (1:(nrow(mat)-abs(n)))) {
  20. elem <- if (n > 0) {
  21. mat[i, i+n] <- value[i]
  22. } else {
  23. mat[i+abs(n), i] <- value[i]
  24. }
  25. }
  26. return(mat)
  27. }
  28. mat <- matrix(1:16, nrow=4)
  29. print(mat)
  30. print(n_diag(mat, 2))
  31. n_diag(mat, -3) <- 1
  32. print(mat)