如何取一行二维数组?

时间:2015-07-30 05:42:03

标签: c# arrays multidimensional-array

我希望使用C#进行双三次插值,但我不能处理数组。

 double cubicInterpolate(double[] p , double x)
    {
        return p[1] + 0.5 * x * (p[2] - p[0] + x * (2.0 * p[0] - 5.0 * p[1] + 4.0 * p[2] - p[3] + x * (3.0 * (p[1] - p[2]) + p[3] - p[0])));
    }

    double bicubicInterpolate(double[,] p , double x, double y)
    {
        double [] arr = new double[4];
        arr[0] = cubicInterpolate(p[][0], y);
        arr[1] = cubicInterpolate(p[][1], y);
        arr[2] = cubicInterpolate(p[][2], y);
        arr[3] = cubicInterpolate(p[][3], y);
        return cubicInterpolate(arr, x);
    }

1 个答案:

答案 0 :(得分:2)

基本上,你不能。你有一个矩形数组,这是一个单独的内存块。您可以编写自己的包装器,例如

public RectangularArrayRow<T> : IList<T>
{
    private readonly int row;
    private readonly T[,] array;

    public RectangularArrayRow(T[,] array, int row)
    {
        // TODO: Validation
        this.row = row;
        this.array = array;
    }

    public T this[int index]
    {
        get { return array[row, index]; }
        set { array[row, index] = value; }
    }

    // etc
}

但是如果你想直接获得一个“子阵列”,你需要使用锯齿状的数组开始:

double[][] array = new double[10][];
for (int i = 0; i < array.Length; i++)
{
     array[i] = new double[3];
}
// ...
double[] row = array[0]; // or whatever

所以你的bicubicInterpolate方法将成为:

// Note: name changed to to be conventional
double BicubicInterpolate(double[][] p, double x, double y)
{
    double[] arr = new double[4];
    arr[0] = CubicInterpolate(p[0], y);
    arr[1] = CubicInterpolate(p[1], y);
    arr[2] = CubicInterpolate(p[2], y);
    arr[3] = CubicInterpolate(p[3], y);
    return CubicInterpolate(arr, x);
}