找到密集矩阵的平均值

时间:2012-06-20 17:50:30

标签: c# visual-studio matrix mean

我正在尝试计算C#中密集矩阵中每列的算术平均值,但我想知道它是否可以完成?

1 个答案:

答案 0 :(得分:0)

元代码

mean(int[,] data, int j)    
   int sum = 0;    
   for i=0 to data.Length - 1
      sum += data [i, j]
   end     
   return sum / data.Length;

C#代码

class Program
{
    static void Main(string[] args)
    {
        var data = new[,]
        {
            { 1.1, 2.2 }, 
            { 3.3, 4.4 }, 
            { 5.5, 6.6 }, 
            { 7.7, 8.8 }
        };

        double meanValue = Mean(data, 0);
    }

    public static double Mean(double[,] data, int columnIndex)
    {
        double sum = 0.0;
        int rowsCount = data.GetLength(0);

        for (int i = 0; i < rowsCount - 1; i++)
        {
            sum += data[i, columnIndex];
        }

        return sum / rowsCount;
    }
}