2014-01-09 106 views
1

我要填充三維陣列具有以下的數組:如何填寫三維陣列

double[] y11 = new double[7] { 24, 13.3, 12.2, 14, 22.2, 16.1, 27.9 }; 
double[] y12 = new double[7] { 3.5, 3.5, 4, 4, 3.6, 4.3, 5.2 }; 

double[] y21 = new double[7] { 7.4, 13.2, 8.5, 10.1, 9.3, 8.5, 4.3 }; 
double[] y22 = new double[7] { 3.5, 3, 3, 3, 2, 2.5, 1.5 }; 

double[] y31 = new double[5] { 16.4, 24, 53, 32.7, 42.8 }; 
double[] y32 = new double[5] { 3.2, 2.5, 1.5, 2.6, 2 }; 

double[] y41 = new double[2] { 25.1, 5.9 }; 
double[] y42 = new double[2] { 2.7, 2.3 }; 

例如Y12意味着在組1中,列號2等的陣列。所以我有4組,每組有2列。

public class Matrix 
{ 
    double[, ,] matrix; 
    public void Initial(int groupSize, int columnSize, int valueSize) 
    { 
     matrix = new double[groupSize, columnSize, valueSize]; 
    } 
} 

我需要一個簡單靈活的Add方法爲基質,而不是像分配matrix[1][2][3] = value;

我已經試過這每一個值,但無法得到它的工作

public void Add(double[] columnArray, int groupIndex, int columnIndex) 
{ 
    matrix[i, y] = columnArray; 
} 
+2

如果你讓'雙[] []矩陣;'你可以使用一個單一的任務,但是這是一個淺拷貝。不同的尺寸似乎也需要這個。 –

+0

@HenkHolterman我混淆了哪一個,'[groupSize] [columnSize,valueSize]'那樣? –

+0

[組,列] [valueIndex] –

回答

1

根據to @Henk Holterman的評論(謝謝),我設法解決了這個問題

public class Matrix 
{ 
    double[,][] matrix; 
    public Matrix(int groupSize, int columnSize) 
    { 
     matrix = new double[groupSize, columnSize][]; 
    } 
    public void Add(double[] arr, int groupIndex, int columnIndex) 
    { 
     matrix[groupIndex, columnIndex] = arr; 
    } 
    public void Print() 
    { 
     int columnIndex = 0; 
     int groupIndex = 0; 
     int groupSize = matrix.GetLength(0); 
     int columnSize = matrix.GetLength(1); 
     while (groupIndex < groupSize) 
     { 
      for (int k = 0; k < matrix[groupIndex, columnIndex].Length; k++) 
      { 
       Console.Write(groupIndex + 1); 
       while (columnIndex < columnSize) 
       { 
        Console.Write("  {0}", matrix[groupIndex, columnIndex][k]); 
        columnIndex++; 
       } 
       Console.WriteLine(); 
       columnIndex = 0; 
      } 
      groupIndex++; 
     } 
    } 

} 

主類

static Matrix m; 
    static void SetDataSet() 
    { 
     double[] y11 = new double[7] { 24, 13.3, 12.2, 14, 22.2, 16.1, 27.9 }; 
     double[] y12 = new double[7] { 3.5, 3.5, 4, 4, 3.6, 4.3, 5.2 }; 

     double[] y21 = new double[7] { 7.4, 13.2, 8.5, 10.1, 9.3, 8.5, 4.3 }; 
     double[] y22 = new double[7] { 3.5, 3, 3, 3, 2, 2.5, 1.5 }; 

     double[] y31 = new double[5] { 16.4, 24, 53, 32.7, 42.8 }; 
     double[] y32 = new double[5] { 3.2, 2.5, 1.5, 2.6, 2 }; 

     double[] y41 = new double[2] { 25.1, 5.9 }; 
     double[] y42 = new double[2] { 2.7, 2.3 }; 

     m.Add(y11, 0, 0); 
     m.Add(y12, 0, 1); 
     m.Add(y21, 1, 0); 
     m.Add(y22, 1, 1); 
     m.Add(y31, 2, 0); 
     m.Add(y32, 2, 1); 
     m.Add(y41, 3, 0); 
     m.Add(y42, 3, 1); 
    } 
    static void Main(string[] args) 
    { 
     m = new Matrix(4,2); 
     SetDataSet(); 
     m.Print(); 
     Console.ReadLine(); 
    } 
} 

enter image description here