如何从2D数组中获取1D列数组和1D行数组?(C#.NET)

Jos*_*iwi 9 .net c# arrays 2d rows

我有double[,] Array;.是否有可能得到类似的东西double[] ColumnArray0 = Array[0,].toArray(),double[] RowArray1 = Array[,1].toArray()而不是制作每个elemet的副本(用于)?

谢谢.

Tim*_*try 8

虽然很晚,但我想提出一个问题的替代答案.

问题的第一个重要部分是能够访问矩阵的完整行或列.这样做的一种可能性是使用扩展方法:

public static class MatrixExtensions
{
  /// <summary>
  /// Returns the row with number 'row' of this matrix as a 1D-Array.
  /// </summary>
  public static T[] GetRow<T>(this T[,] matrix, int row)
  {
    var rowLength = matrix.GetLength(1);
    var rowVector = new T[rowLength];

    for (var i = 0; i < rowLength; i++)
      rowVector[i] = matrix[row, i];

    return rowVector;
  }



  /// <summary>
  /// Sets the row with number 'row' of this 2D-matrix to the parameter 'rowVector'.
  /// </summary>
  public static void SetRow<T>(this T[,] matrix, int row, T[] rowVector)
  {
    var rowLength = matrix.GetLength(1);

    for (var i = 0; i < rowLength; i++)
      matrix[row, i] = rowVector[i];
  }



  /// <summary>
  /// Returns the column with number 'col' of this matrix as a 1D-Array.
  /// </summary>
  public static T[] GetCol<T>(this T[,] matrix, int col)
  {
    var colLength = matrix.GetLength(0);
    var colVector = new T[colLength];

    for (var i = 0; i < colLength; i++)
      colVector[i] = matrix[i, col];

    return colVector;
  }



  /// <summary>
  /// Sets the column with number 'col' of this 2D-matrix to the parameter 'colVector'.
  /// </summary>
  public static void SetCol<T>(this T[,] matrix, int col, T[] colVector)
  {
    var colLength = matrix.GetLength(0);

    for (var i = 0; i < colLength; i++)
      matrix[i, col] = colVector[i];
  }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

double[,] myMatrix = ... // Initialize with desired size and values.
double[] myRowVector = myMatrix.GetRow(2); // Gets the third row.
double[] myColVector = myMatrix.GetCol(1); // Gets the second column.
myMatrix.SetCol(2, myColVector); // Sets the third column to the second column.
Run Code Online (Sandbox Code Playgroud)

首先要注意的是,您可以将这些通用方法与任何类型的[,] - 矩阵和相应的[] -vectors一起使用.想象一下用Ts 替换doubles,你会得到'double'的特定版本(正如OP所要求的那样).

第二件事是,获取和设置行使用Array.Copy,而获取和设置列使用循环.这是由于C#的Row-Major顺序,它允许第一个,但不允许第二个.当然,两者都可以通过循环实现,如下所示.

确保为set-Methods传递正确的尺寸,否则程序将崩溃(可以轻松添加错误和尺寸检查).整个逻辑也可以用于锯齿状数组double[][],但是,OP特别要求多维数据.

至于问题的第二部分:如果矩阵由double组成,并且double是值类型,则将始终复制值.因此,您不希望复制值的行为.但是,如果使用对象T,则只会复制指向对象的引用,而不是对象本身(因此要注意改变'复制'对象).

最后,如果你真的不想复制双值,我建议传递整个矩阵(只传递引用),然后直接循环遍历所需的列和/或行.


tha*_*alm 6

数组是一个内存区域,所有条目都以连续方式存储在其中。根据内存中的数据布局,这仅适用于行或列。

double[,]在您的情况下,最好使用数组数组而不是 2d 数组类型double[][]

double[][] Array2d = new double[10][];
Array2d[0] = new double[10];
Array2d[1] = new double[10];
...

and then:
double[] RowArray0 = Array2d[0];
Run Code Online (Sandbox Code Playgroud)

根据您将数据放入数组的方式,您还可以将其Array2d视为列数组。但同时拥有两者是不可能的。

也看看这里: 多维数组 [][] vs [,]

  • 那么,如果数组是使用 `[,]` 定义的,那么有没有办法做到这一点? (25认同)