我有一个函数应用于二维数组 ( double[,]
) 的每个元素,但仅沿给定维度。
我不得不创建两个函数,因为我不知道如何将所需的维度作为参数传递给方法。我最终得到了一个“vertical_foo”和一个“horizontal_foo”函数,它们几乎相同:
private double[,] vertical_foo (double[,] a) {
int height = a.GetLength(0);
int width = a.GetLength(1);
var result = new double[height, weight];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
// Here I use first ("i") dimension
int before = Math.Max(i-1, 0);
int after = Math.Min(i+1, height-1);
result[i,j] = (a[after, j] - a[before, j]) * 0.5;
}
}
return result;
}
private double[,] horizontal_foo (double[,] a) {
int height = a.GetLength(0);
int width = a.GetLength(1);
var result = new double[height, weight];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
// Here I use second ("j") dimension
int before = Math.Max(j-1, 0);
int after = Math.Min(j+1, height-1);
result[i,j] = (a[i, after] - a[i, before]) * 0.5;
}
}
return result;
}
我想要这样的签名,其中第二个参数是我要应用索引的维度:
private double[,] general_foo (double[,] a, int dimension) {}
非常欢迎任何建议!