Surbhi
Surbhi

Reputation: 111

Using LinEst () in .net

I want to use Excel's buil-in function called LINEST() to do regression analysis in .net. I am able to use the function with squred matrix array, but when it is not square matrix say of order[12,3] then it gives error as:

LinEst method of WorksheetFunction class failed

Please help me out with this as it is very important for me to complete this code. This is my complete code:

        System.Data.DataTable dt = new System.Data.DataTable();
        SqlCommand  cmd =new SqlCommand("Select QtytoTransfer from DEmo ",con);

        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(dt);

        List<double> yDatapoints =new List<double>();

        foreach (DataRow dr in dt.Rows)
        {
            yDatapoints.Add(Convert.ToDouble( dr["QtytoTransfer"].ToString()));
        }



        System.Data.DataTable dt1 = new System.Data.DataTable();

        SqlCommand sqlcmd = new SqlCommand("Select CurrentQoh,QtySold,GameTime from DEmo ", con);

        SqlDataAdapter adp1 = new SqlDataAdapter(sqlcmd);
        adp1.Fill(dt1);

        double[,] xAll = new double[dt1.Rows.Count, dt1.Columns.Count];
        for (int i = 0; i < dt1.Rows.Count; ++i)
        {
            for (int j = 0; j < dt1.Columns.Count; ++j)
            {
                xAll[i, j] = Convert.ToDouble(dt1.Rows[i][j].ToString());
            }
        }

        Microsoft.Office.Interop.Excel.Application xl = new Microsoft.Office.Interop.Excel.Application();

        Microsoft.Office.Interop.Excel.WorksheetFunction wsf = xl.WorksheetFunction;
        object[,] reslut = (object[,])wsf.LinEst(yDatapoints.ToArray(), xAll, missing, true);

Upvotes: 0

Views: 2642

Answers (2)

Reeder Ward II
Reeder Ward II

Reputation: 11

Here's an implementation of Excel's LINEST() function in C#. It might be easier than creating a dependency on the Microsoft.Office.Interop.Excel DLL file.

This returns the slope for a given set of data, normalized using the same "least squares" method that LINEST() uses:

public static double CalculateLinest(double[] y, double[] x)
{
   double linest = 0;
   if (y.Length == x.Length)
   {
      double avgY = y.Average();
      double avgX = x.Average();
      double[] dividend = new double[y.Length];
      double[] divisor = new double[y.Length];
      for (int i = 0; i < y.Length; i++)
      {
         dividend[i] = (x[i] - avgX) * (y[i] - avgY);
         divisor[i] = Math.Pow((x[i] - avgX), 2);
      }
      linest = dividend.Sum() / divisor.Sum();
   }
   return linest;
}

Also, here's a method I wrote to get the "b" (y-intercept) value that Excel's LINEST function generates.

private double CalculateYIntercept(double[] x, double[] y, double linest)
{
    return (y.Average() - linest * x.Average());
}

Since these methods only work for one set of data, I would recommend calling them inside of a loop if you wish to produce multiple sets of linear regression data.

This link helped me find my answer: https://agrawalreetesh.blogspot.com/2011/11/how-to-calculate-linest-of-given.html

Upvotes: 0

cgon
cgon

Reputation: 1981

if your xAll has a dimension of [12,3] your yDataPoints length should be 3 for proper functioning of LinEst().

using System;

namespace InteropExcel {
    class Program {
        static void Main(string[] args) {
            Random rand = new Random();
            double[] yDatapoints = new double[3];
            for (int i = 0; i < 3; i++) {
                yDatapoints[i]=rand.Next(20, 60);
            }
            double[,] xAll = new double[12, 3];
            for (int i = 0; i < 12; i++) {
                for (int j = 0; j < 3; j++) {

                    xAll[i, j] = rand.Next(2, 100);
                }
            }
            Microsoft.Office.Interop.Excel.Application xl = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.WorksheetFunction wsf = xl.WorksheetFunction;
            object[,] result = (object[,])wsf.LinEst(yDatapoints, xAll, Type.Missing, true);



        }
    }
}

The column size of xAll should be equal to the length of yDataPoints array. Please try and let me know.

Upvotes: 2

Related Questions