我有double[,] Array;
。是否有可能得到像double[] ColumnArray0 = Array[0,].toArray()
和double[] RowArray1 = Array[,1].toArray()
之類的東西,而沒有製作每個elemet(用於)的副本?如何從2D數組中獲取1D列數組和1D行數組? (C#.NET)
謝謝。
我有double[,] Array;
。是否有可能得到像double[] ColumnArray0 = Array[0,].toArray()
和double[] RowArray1 = Array[,1].toArray()
之類的東西,而沒有製作每個elemet(用於)的副本?如何從2D數組中獲取1D列數組和1D行數組? (C#.NET)
謝謝。
數組是一個內存區域,所有條目都以連續的方式存儲。根據內存中的數據佈局,這僅適用於行或列。
取而代之的是二維數組double[,]
類是你的情況最好使用數組double[][]
double[][] Array2d = new double[10][];
Array2d[0] = new double[10];
Array2d[1] = new double[10];
...
and then:
double[] RowArray0 = Array2d[0];
取決於你如何把數據數組中的數組,你還可以治療Array2d
作爲列數組。但是同時擁有這兩個東西是不可能的。
也可以看看這裏: Multidimensional Array [][] vs [,]
所以,如果數組是用[[,]'定義沒有辦法做到這一點? – AdamMc331
雖然是很晚了,我想提供一個備選答案的問題。
問題的第一個重要部分是能夠訪問矩陣的完整行或列。這樣做的一種可能是通過使用擴展方法:
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];
}
}
用例:
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.
首先要注意的是,你可以使用這些通用的方法,與任何一種[日] - 矩陣和對應的[] - 向量。想象一下用double
代替T
s,你會得到'double'的特定版本(正如OP所要求的那樣)。
第二件事,獲取和設置行使用Array.Copy
,而獲取和設置列使用循環。這是由於C#的Row-Major order,它允許第一個,但不是第二個。當然,兩者都可以用一個循環來實現,正如所看到的那樣。
確保爲set-Methods傳遞了正確的尺寸,否則程序將崩潰(可以輕鬆添加錯誤和尺寸檢查)。整個邏輯也可以用於像double[][]
這樣的鋸齒狀數組,但是,OP特別要求提供多維數組。
至於問題的第二部分:如果您的矩陣由double組成,並且double是值類型,則值將始終被複制。所以你不想複製這些值的行爲是不可能的。但是,如果使用對象作爲T
,則只會複製指向該對象的引用,而不會複製對象本身(因此請小心修改「複製的」對象)。最後,如果你真的不想複製double值,我建議傳遞你的整個矩陣(只傳遞參考),然後直接遍歷所需的列和/或行。
我不明白你的問題,但爲什麼你需要這樣做? –
我試圖在圖像(2D陣列)上實現FFT,並通過一維FFT調用在行上然後在柱上實現。不要做任何不必要的數組或循環會很好。(FFT是時間和內存消耗) –
我想你不應該自己實現圖像處理算法,在C#中尋找FFT圖像,你可能會發現人們已經做到了。它可能實現OpenCV的C# 或如果它不是爲了生產的目的,只要堅持matlab或類似的 –