我想用以下数组填充三维数组:
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;
}
答案 0 :(得分:1)
根据@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();
}
}