Ich habe eine einfache Matrix:mittelt in einer Matrix bewegen - Fenster außerhalb der Grenzen
x <- seq (1:100)
matrix_A = matrix(x, ncol = 10)
matrix_A
ich alle Werte mit einem laufenden Fenster der Größe 3 x 3
Einfache Funktion zu tun mitteln will dass:
running_window_v1 <- function(mat.temp){
#Create an empty matrix to store calculations in it
mat.temp1=matrix(NA,ncol = ncol(mat.temp), nrow = nrow(mat.temp))
for (i in (1 : (nrow(mat.temp)))){
for (j in (1 : (ncol(mat.temp)))){
mat.temp1[i,j] = mean (mat.temp[i - 1, j - 1],
mat.temp[i - 1, j],
mat.temp[i- 1, j + 1],
mat.temp[i, j - 1],
mat.temp[i, j],
mat.temp[i, j + 1],
mat.temp[i + 1, j - 1],
mat.temp[i + 1, j],
mat.temp[i +1, j + 1])
}
}
return(mat.temp1)
}
running_window_v1(matrix_A)
Das Problem bei diesem Skript offensichtlich ist, dass ich Fehler bekommen, denn wenn (zB) i = 1
, j = 1
, ich rufe Werte, die in der Matrix nicht vorhanden matrix_A[- 1, - 1]
. So Funktion nur funktionieren würde, wenn ich es auf folgende Weise ändern:
running_window_v2 <- function(mat.temp){
#Create an empty matrix to store calculations in it
mat.temp1=matrix(NA,ncol = ncol(mat.temp), nrow = nrow(mat.temp))
for (i in (2 : (nrow(mat.temp)-1))){
for (j in (2 : (ncol(mat.temp)-1))){
mat.temp1[i,j] = mean (mat.temp[i - 1, j - 1],
mat.temp[i - 1, j],
mat.temp[i- 1, j + 1],
mat.temp[i, j - 1],
mat.temp[i, j],
mat.temp[i, j + 1],
mat.temp[i + 1, j - 1],
mat.temp[i + 1, j],
mat.temp[i +1, j + 1])
}
}
return(mat.temp1)
}
> running_window_v2(matrix_A)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] NA NA NA NA NA NA NA NA NA NA
[2,] NA 1 11 21 31 41 51 61 71 NA
[3,] NA 2 12 22 32 42 52 62 72 NA
[4,] NA 3 13 23 33 43 53 63 73 NA
[5,] NA 4 14 24 34 44 54 64 74 NA
[6,] NA 5 15 25 35 45 55 65 75 NA
[7,] NA 6 16 26 36 46 56 66 76 NA
[8,] NA 7 17 27 37 47 57 67 77 NA
[9,] NA 8 18 28 38 48 58 68 78 NA
[10,] NA NA NA NA NA NA NA NA NA NA
Für meine Arbeit ist es wirklich wichtig, dass ich die Informationen nicht verlieren und ich brauche auch die Kanten mitteln (natürlich mit weniger Zahlen). Hast du irgendwelche Vorschläge, wie ich Funktion running_window_v1
ändern könnte, um für mich gut zu funktionieren? Ich verstehe, ich könnte zusätzliche Bedingungen für jede mögliche Kante schreiben, aber ich suche nach eleganterem Zustand.
Ja, das ist die Antwort. Vielen Dank. – JerryTheForester