public static Double Det(Double[,] matrix)
        {
            var rows    = matrix.GetLength(0);
            var columns = matrix.GetLength(1);

            if (rows == columns)
            {
                switch (rows)
                {
                case 0: return(0.0);

                case 1: return(matrix[0, 0]);

                case 2: return(Helpers.Det2(matrix));

                case 3: return(Helpers.Det3(matrix));

                case 4: return(Helpers.Det4(matrix));
                }

                return(LUDecomposition.Determinant(matrix));
            }

            return(0.0);
        }
Beispiel #2
0
        /// <summary>
        /// Converts the matrix to a string.
        /// </summary>
        public static String This(Double[,] value)
        {
            var sb   = StringBuilderPool.Pull();
            var rows = value.GetLength(0);
            var cols = value.GetLength(1);

            sb.Append('[');

            for (var i = 0; i < rows; i++)
            {
                if (i > 0)
                {
                    sb.Append(';');
                }

                for (var j = 0; j < cols; j++)
                {
                    if (j > 0)
                    {
                        sb.Append(',');
                    }

                    sb.Append(value[i, j].ToString(CultureInfo.InvariantCulture));
                }
            }

            sb.Append(']');
            return(sb.Stringify());
        }
Beispiel #3
0
 public static double TemplateEquals(Double[,] a, Double[,] b)
 {
     try
     {
         if (a.Length != b.Length)
         {
             return(0);
         }
         int    elementCount = 0;
         double percent      = 0;
         int    tot          = a.GetLength(0) * a.GetLength(1);
         for (int i = 0; i < a.GetLength(0); i++)
         {
             for (int j = 0; j < a.GetLength(1); j++)
             {
                 if (a[i, j] == b[i, j])
                 {
                     elementCount++;
                     //percent = (double)((double)(elementCount / tot)) * 100;
                 }
             }
         }
         double v1 = (double)((double)elementCount / (double)tot);
         double v2 = (double)(v1 * 100);
         percent = v2;
         return(percent);
     }
     catch (Exception ex)
     {
         st.WMsgBox(ex.ToString());
         return(0);
     }
 }
Beispiel #4
0
        public int RecognizeNewFace(byte[] newPerson)
        {
            Double[] img = new Double[newPerson.Count()];

            for (int i = 0; i < newPerson.Length; i++)
            {
                img[i] = newPerson[i];
            }


            Double[] projection = pca.Transform(img);
            int      best       = 0;
            double   distance   = double.MaxValue;

            for (int i = 0; i < R.GetLength(1); i++)
            {
                double sum = 0;

                for (int j = 0; j < R.GetLength(0); j++)
                {
                    sum += Math.Pow(projection[j] - R[i, j], 2);
                }

                if (sum < distance)
                {
                    distance = sum;
                    best     = i;
                }
            }

            return(best);
        }
Beispiel #5
0
        private void VmaxEst()
        {
            Vmax1_set = new List <double>();
            AltitudeCalculator.CalcAtmos(txt_Height_cr.Text, cmbHeight_cr);
            CalculateK();
            int i = 0;

            while (i < W_surf.Length)
            {
                Double abc = Vmax_Prop.Perf_Vmax_Prop(W_surf[i], K, CDmin, Wto_guess, 0.75 * MinPow, PropEffi);
                Vmax1_set.Add(Math.Round(abc / 1.688, 0));

                i += 1;
            }
            Max_V = new Double[8, 8];
            for (int j = 0; j < Vmax1_set.Count(); j += 1)
            {
                for (int k = 0; k < Vmax1_set.Count(); k += 1)
                {
                    Max_V[k, j] = Vmax1_set[k];
                }
            }

            for (int m = 0; m < Max_V.GetLength(0); m++)
            {
                string[] row = new string[Max_V.GetLength(1)];

                for (int j = 0; j < Max_V.GetLength(1); j++)
                {
                    row[j] = Max_V[j, m].ToString();
                }

                dataGridView2.Rows.Add(row);
            }
        }
Beispiel #6
0
        private void CarpetPlot()
        {
            Vs_set   = new Double[8, 8];
            WingArea = new List <double>();
            MaxCl    = new List <double>();


            for (int i = 0; i < W_surf.Length; i++)
            {
                for (int j = 0; j < CL_max.Length; j++)
                {
                    WingArea.Add(W_surf[i]);
                    MaxCl.Add(CL_max[j]);
                    Double Vs = Math.Sqrt((2 * Wto_guess) / (AltitudeCalculator.Dens_Standard * 0.00194 * W_surf[i] * CL_max[j]));
                    Vs_set[i, j] = Math.Round(Vs / 1.688, 0);
                }
            }

            for (int i = 0; i < Vs_set.GetLength(0); i++)
            {
                string[] row = new string[Vs_set.GetLength(1)];

                for (int j = 0; j < Vs_set.GetLength(1); j++)
                {
                    row[j] = Vs_set[j, i].ToString();
                }

                dataGridView1.Rows.Add(row);
            }
        }
Beispiel #7
0
        }//end getKrigedGageValue
        private Double[,] GetVarianceWeights(Double[,] I, Double[,] D)
        {
            //the set of wieghts that provide unbiased estimates with a minimum estimation variance is calculated by 
            //multiplying the inverted covariance matrix(I or C^-1) by the ungaged covarinace matrix (D matrix)
            //Isaaks, E. H., and R. M. Srivastava (1989), An Introduction to Applied
            //		Geostatistics, 1st ed., Oxford Univ. Press, New York. pg295
            int matrixLength = 0;
            Double wSum = 0;
            Double[,] w = null;
            try
            {
                if (I.GetLength(0) != D.GetLength(0) ||
                    I.GetLength(1) != D.GetLength(0)) throw new Exception("rows != columns");

                matrixLength = I.GetLength(0);

                w = new Double[matrixLength, 1];
                for (int i = 0; i < matrixLength; i++)
                {
                    wSum = 0;
                    for (int j = 0; j < matrixLength; j++)
                    {
                        // matrix DOT product
                        wSum = wSum + I[i, j] * D[j, 0];
                    }//next r
                    w[i, 0] = wSum;
                }//next i

                return w;
            }
            catch (Exception e)
            {
                throw;
            }//end try
        }//end getVarianceWeights
        /// <summary>Constructs a new Cholesky Decomposition.</summary>
        ///
        /// <param name="value">The matrix to be decomposed.</param>
        /// <param name="robust">True to perform a square-root free LDLt decomposition,
        /// false otherwise.</param>
        /// <param name="lowerTriangular">True to assume the <paramref name="value">value
        /// matrix</paramref> is a lower triangular symmetric matrix, false otherwise.</param>
        ///
        public CholeskyDecomposition(Double[,] value, bool robust, bool lowerTriangular)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value", "Matrix cannot be null.");
            }

            if (value.GetLength(0) != value.GetLength(1))
            {
                throw new DimensionMismatchException("value", "Matrix is not square.");
            }

            if (robust)
            {
                LDLt(value); // Compute square-root free decomposition
            }
            else
            {
                LLt(value); // Compute standard Cholesky decomposition
            }

            if (lowerTriangular)
            {
                symmetric = true;
            }
        }
Beispiel #9
0
 /// <summary>
 /// QR Decomposition, computed by Householder reflections.
 /// </summary>
 /// <param name="A">Rectangular matrix</param>
 /// <returns>Structure to access R and the Householder vectors and compute Q.</returns>
 protected QRDecomposition(Double[,] A)
 {
     // Initialize.
     HasFullRank = true;
     _rows       = A.GetLength(0);
     _columns    = A.GetLength(1);
 }
Beispiel #10
0
        public static Double[,] Multiply(Double[,] a, Double[,] b)
        {
            var rows   = a.GetLength(0);
            var cols   = b.GetLength(1);
            var length = a.GetLength(1);

            if (length == b.GetLength(0))
            {
                var result = new Double[rows, cols];

                for (var i = 0; i < rows; i++)
                {
                    for (var j = 0; j < cols; j++)
                    {
                        var value = 0.0;

                        for (var k = 0; k < length; k++)
                        {
                            value += a[i, k] * b[k, j];
                        }

                        result[i, j] = value;
                    }
                }

                return(result);
            }

            return(null);
        }
Beispiel #11
0
        public void Import(Double[,] coordinate)
        {
            try
            {
                // Format Check
                var rowNo    = coordinate.GetLength(0);
                var columnNo = coordinate.GetLength(1);
                if (columnNo != 2)
                {
                    throw new FormatException();
                }

                // Clear coordinate List
                CoordinateList.Clear();

                // Add coordinate
                for (int i = 0; i < rowNo; i++)
                {
                    var dataRpw = new Double[2];
                    for (int j = 0; j < columnNo; j++)
                    {
                        dataRpw[j] = coordinate[i, j];
                    }
                    CoordinateList.Add(dataRpw);
                }
                Length = CoordinateList.Count;
            }
            catch (FormatException)
            {
            }
        }
Beispiel #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        /// <exception cref="FormatException"/>
        private ObservableCollection <EachCoefficients> ConvertDoubleArrayToObservable(Double[,] array)
        {
            var length = array.GetLength(0);
            var width  = array.GetLength(1);

            // Format Check
            if (width != GeneralConstants.NUMBER_OF_AIRFOILS_OF_GENERATION)
            {
                throw new FormatException("width of array of coefficient is invalid");
            }

            var oCollection = new ObservableCollection <EachCoefficients>();

            for (int i = 0; i < length; i++)
            {
                oCollection.Add(new EachCoefficients()
                {
                    Airfoil1  = array[i, 0],
                    Airfoil2  = array[i, 1],
                    Airfoil3  = array[i, 2],
                    Airfoil4  = array[i, 3],
                    Airfoil5  = array[i, 4],
                    Airfoil6  = array[i, 5],
                    Airfoil7  = array[i, 6],
                    Airfoil8  = array[i, 7],
                    Airfoil9  = array[i, 8],
                    Airfoil10 = array[i, 9],
                });
            }

            return(oCollection);
        }
Beispiel #13
0
        /// <summary>
        /// Least squares solution of A * X = B
        /// </summary>
        /// <param name="b">A Matrix with as many rows as A and any number of columns.</param>
        /// <returns>X that minimizes the two norm of Q*R*X-B.</returns>
        public override Double[,] Solve(Double[,] b)
        {
            if (b.GetLength(0) != _rows)
            {
                throw new InvalidOperationException(ErrorMessages.RowMismatch);
            }

            if (!HasFullRank)
            {
                throw new InvalidOperationException(ErrorMessages.SingularSource);
            }

            var cols = b.GetLength(1);

            var r = Helpers.Multiply(Helpers.Transpose(Q), b);
            var x = new Double[_columns, cols];

            for (var j = _columns - 1; j >= 0; j--)
            {
                for (var i = 0; i < cols; i++)
                {
                    var o = 0.0;

                    for (var k = j; k < _columns; k++)
                    {
                        o += R[j, k] * x[k, i];
                    }

                    x[j, i] = (r[j, i] - o) / R[j, j];
                }
            }

            return(x);
        }
        /// <summary>
        /// Substitute this instance.
        /// </summary>
        public void Substitute()
        {
            int    degrees = upperMatrix.Rank;
            int    rows    = upperMatrix.GetLength(0);
            int    cols    = upperMatrix.GetLength(1);
            Double val;

            Double[] coefficients = new Double[rows];
            Console.WriteLine(@"Rows: {0} Cols {1}", rows, cols);
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < rows; j++)
                {
                    coefficients[j] = lowerMatrix[i, j];
                    val             = lowerMatrix[i, rows];
                    Substitution(ref zee, coefficients, val, i);
                }
            }
            Console.WriteLine();
            DisplayAnswer(zee);
            ReplaceBee();
            for (int i = rows - 1; i >= 0; i--)
            {
                for (int j = 0; j < rows; j++)
                {
                    coefficients[j] = upperMatrix[i, j];
                    val             = upperMatrix[i, rows];
                    Substitution(ref bee, coefficients, val, i);
                }
            }
            Console.WriteLine();
            DisplayAnswer(bee);
        }
Beispiel #15
0
        //-----------------------------------------------------------------------------

        static public Double[] MinMax(Double[,] prmData)
        {
            Double min  = Double.MaxValue;
            Double max  = Double.MinValue;
            Int32  rows = prmData.GetLength(0);
            Int32  cols = prmData.GetLength(1);

            int i, j;

            for (i = 0; i < rows; i++)
            {
                for (j = 0; j < cols; j++)
                {
                    if (prmData[i, j] < min)
                    {
                        min = prmData[i, j];
                    }
                    if (prmData[i, j] > max)
                    {
                        max = prmData[i, j];
                    }
                }
            }
            return(new Double[2] {
                min, max
            });
        }
Beispiel #16
0
        /// <summary>
        /// Guassian the specified matrix.
        /// </summary>
        /// <returns>The guassian.</returns>
        /// <param name="matrix">Matrix.</param>
        private static void Guassian(ref Double[,] matrix)
        {
            DisplayMatrix(matrix);
            int degrees = matrix.Rank;
            int rows    = matrix.GetLength(0);
            int cols    = matrix.GetLength(1);

            Double[] firstRow  = new Double[cols];
            Double[] secondRow = new Double[cols];

            for (int i = 0; i < rows - 1; i++)
            {
                for (int j = i; j < rows - 1; j++)
                {
                    for (int k = 0; k < cols; k++)
                    {
                        firstRow[k] = matrix[i, k];

                        if (j + 1 < rows)
                        {
                            secondRow[k] = matrix[j + 1, k];
                        }
                    }
                    if (i + 1 < rows)
                    {
                        Console.WriteLine(@"Multiplier:  {0} ", Multiplier(firstRow, secondRow, i));
                        ReplaceMatrix(ref matrix, Elimination(firstRow, secondRow, Multiplier(firstRow, secondRow, i)), j + 1);
                        DisplayMatrix(matrix);
                    }
                }
            }
        }
Beispiel #17
0
        private static object MMult(List <Expression> p)
        {
            Double[,] A = GetArray(p[0]);
            Double[,] B = GetArray(p[1]);

            if (A.GetLength(0) != B.GetLength(0) || A.GetLength(1) != B.GetLength(1))
            {
                throw new ArgumentException("Ranges must have the same number of rows and columns.");
            }

            var C = new double[A.GetLength(0), A.GetLength(1)];

            for (int i = 0; i < A.GetLength(0); i++)
            {
                for (int j = 0; j < B.GetLength(1); j++)
                {
                    for (int k = 0; k < A.GetLength(1); k++)
                    {
                        C[i, j] += A[i, k] * B[k, j];
                    }
                }
            }


            return(C);
        }
Beispiel #18
0
        public static void SetDetailofLevel(Double[] input, Double[,] coefs, Int32 level)
        {
            Int32 Len      = coefs.GetLength(0) >> level;
            Int32 InpIndex = 0;

            Int32 lev   = level;
            Int32 Bound = coefs.GetLength(0) >> lev - 1;

            Len = coefs.GetLength(0) >> lev;
            for (int i = 0; i < Len; i++)
            {
                for (int j = Len; j < Bound; j++)
                {
                    coefs[i, j] = input[InpIndex];
                    InpIndex++;
                }
            }
            for (int i = Len; i < Bound; i++)
            {
                for (int j = 0; j < Len; j++)
                {
                    coefs[i, j] = input[InpIndex];
                    InpIndex++;
                }
            }
            for (int i = Len; i < Bound; i++)
            {
                for (int j = Len; j < Bound; j++)
                {
                    coefs[i, j] = input[InpIndex];
                    InpIndex++;
                }
            }
        }
Beispiel #19
0
 public DIANA(Double[,] padroes, int k, int tipoDiametro)
 {
     this.padroes        = padroes;
     this.totalGrupos    = k;
     this.tipoDiametro   = tipoDiametro;
     quantidadePadroes   = padroes.GetLength(0);
     quantidadeAtributos = padroes.GetLength(1);
 }
Beispiel #20
0
 public BackwardSubstitution(Double[,] matrix)
 {
     this.matrix = matrix;
     answers     = new Double[matrix.GetLength(0)];
     for (int i = 0; i < matrix.GetLength(0); i++)
     {
         answers[i] = 1;
     }
 }
Beispiel #21
0
        /// <summary>
        /// Least squares solution of A * X = B
        /// </summary>
        /// <param name="matrix">A Matrix with as many rows as A and any number of columns.</param>
        /// <returns>X that minimizes the two norm of Q*R*X-B.</returns>
        public override Double[,] Solve(Double[,] matrix)
        {
            if (matrix.GetLength(0) != _rows)
            {
                throw new InvalidOperationException(ErrorMessages.RowMismatch);
            }

            if (!HasFullRank)
            {
                throw new InvalidOperationException(ErrorMessages.SingularSource);
            }

            // Copy right hand side
            var nx = matrix.GetLength(1);
            var X  = (Double[, ])matrix.Clone();

            // Compute Y = transpose(Q)*B
            for (var k = 0; k < _columns; k++)
            {
                for (var j = 0; j < nx; j++)
                {
                    var s = 0.0;

                    for (var i = k; i < _rows; i++)
                    {
                        s += _QR[i, k] * X[i, j];
                    }

                    s = (-s) / _QR[k, k];

                    for (var i = k; i < _rows; i++)
                    {
                        X[i, j] += s * _QR[i, k];
                    }
                }
            }

            // Solve R * X = Y;
            for (var k = _columns - 1; k >= 0; k--)
            {
                for (var j = 0; j < nx; j++)
                {
                    X[k, j] /= _Rdiag[k];
                }

                for (var i = 0; i < k; i++)
                {
                    for (var j = 0; j < nx; j++)
                    {
                        X[i, j] -= X[k, j] * _QR[i, k];
                    }
                }
            }

            return(Helpers.SubMatrix(X, 0, _columns, 0, nx));
        }
        /// <summary>
        ///   Solves a set of equation systems of type <c>A * X = B</c>.
        /// </summary>
        /// <param name="value">Right hand side matrix with as many rows as <c>A</c> and any number of columns.</param>
        /// <returns>Matrix <c>X</c> so that <c>L * U * X = B</c>.</returns>
        ///
        public Double[,] Solve(Double[,] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if (value.GetLength(0) != rows)
            {
                throw new DimensionMismatchException("value", "The matrix should have the same number of rows as the decomposition.");
            }

            if (!Nonsingular)
            {
                throw new InvalidOperationException("Matrix is singular.");
            }


            // Copy right hand side with pivoting
            int count = value.GetLength(1);

            Double[,] X = value.Submatrix(pivotVector, null);


            // Solve L*Y = B(piv,:)
            for (int k = 0; k < cols; k++)
            {
                for (int i = k + 1; i < cols; i++)
                {
                    for (int j = 0; j < count; j++)
                    {
                        X[i, j] -= X[k, j] * lu[i, k];
                    }
                }
            }

            // Solve U*X = Y;
            for (int k = cols - 1; k >= 0; k--)
            {
                for (int j = 0; j < count; j++)
                {
                    X[k, j] /= lu[k, k];
                }

                for (int i = 0; i < k; i++)
                {
                    for (int j = 0; j < count; j++)
                    {
                        X[i, j] -= X[k, j] * lu[i, k];
                    }
                }
            }

            return(X);
        }
Beispiel #23
0
 public Matrix(Double[,] matrix)
 {
     _matrix = CreateMatrixArray(matrix.GetLength(0), matrix.GetLength(1));
     for (Int32 r = 0; r < CountOfRows; r++)
     {
         for (Int32 c = 0; c < CountOfColumns; c++)
         {
             this[r, c] = matrix[r, c];
         }
     }
 }
        public static Double Trace(Double[,] matrix)
        {
            var length = Math.Min(matrix.GetLength(0), matrix.GetLength(1));
            var sum    = 0.0;

            for (var i = 0; i < length; i++)
            {
                sum += matrix[i, i];
            }

            return(sum);
        }
Beispiel #25
0
 public int GetItem(int x, int y)
 {
     if (x < 0 || y < 0)
     {
         return(0);
     }
     if (x > items.GetLength(0) || y > items.GetLength(1))
     {
         return(0);
     }
     return((int)items[x, y]);
 }
        /// <summary>Solve A*X = B</summary>
        /// <param name="matrix">  A Matrix with as many rows as A and any number of columns.
        /// </param>

        public Double[,] Solve(Double[,] matrix)
        {
            if (matrix.GetLength(0) != _dim)
            {
                throw new InvalidOperationException(ErrorMessages.DimensionMismatch);
            }

            if (!_spd)
            {
                throw new InvalidOperationException(ErrorMessages.SpdRequired);
            }

            // Copy right hand side.
            var X  = (Double[, ])matrix.Clone();
            var nx = matrix.GetLength(1);

            // Solve L*Y = B;
            for (var k = 0; k < _dim; k++)
            {
                for (var i = k + 1; i < _dim; i++)
                {
                    for (var j = 0; j < nx; j++)
                    {
                        X[i, j] -= X[k, j] * _L[i, k];
                    }
                }

                for (var j = 0; j < nx; j++)
                {
                    X[k, j] /= _L[k, k];
                }
            }

            // Solve L'*X = Y;
            for (var k = _dim - 1; k >= 0; k--)
            {
                for (var j = 0; j < nx; j++)
                {
                    X[k, j] /= _L[k, k];
                }

                for (var i = 0; i < k; i++)
                {
                    for (var j = 0; j < nx; j++)
                    {
                        X[i, j] -= X[k, j] * _L[k, i];
                    }
                }
            }

            return(X);
        }
Beispiel #27
0
 public void ActualizarValores()
 {
     try
     {
         //Borrar los valores de [filas 1 y 2] [columna 2]
         int Filas    = MatrizRedimensionada.GetLength(0);
         int Columnas = MatrizRedimensionada.GetLength(1);
         MatrizActualizada = new double[Filas, Columnas];
         // Calculando valores a ingresar en columna 4
         Globals.ValoresFila3_7_Columna4 = Convert.ToDouble(Globals.Total_Fila1_2_Columna2) / 5;
         Console.WriteLine("Las partes iguales para columna 4 seran de (" + Convert.ToDouble(Globals.Total_Fila1_2_Columna2) + "/5): " + Globals.ValoresFila3_7_Columna4);
         Console.WriteLine("---------------------------------------------------------------------------------------------");
         Console.WriteLine("Eliminando los valores de las [filas 1 y 2] [columna 2]");
         Console.WriteLine("---------------------------------------------------------------------------------------------");
         for (int Fila = 0; Fila < Filas; Fila++)
         {
             for (int Columna = 0; Columna < Columnas; Columna++)
             {
                 // Eliminar los valores de la columna 2
                 if (Columna == 1 && Fila == 0 || Columna == 1 && Fila == 1)
                 {
                     MatrizActualizada[Fila, Columna] = 0;
                 }
                 // Agregar las partes iguales en la columna 4
                 else if (Columna == 3 && Fila == 2 || Columna == 3 && Fila == 3 || Columna == 3 && Fila == 4 || Columna == 3 && Fila == 5 || Columna == 3 && Fila == 6)
                 {
                     MatrizActualizada[Fila, Columna] = Globals.ValoresFila3_7_Columna4;
                 }
                 else
                 {
                     MatrizActualizada[Fila, Columna] = MatrizRedimensionada[Fila, Columna];
                 }
             }
         }
         Console.WriteLine("Matriz Actual:");
         for (int Fila = 0; Fila < MatrizActualizada.GetLength(0); Fila++)
         {
             for (int Columna = 0; Columna < MatrizActualizada.GetLength(1); Columna++)
             {
                 // Imprimiendo valores por fila
                 Console.Write(MatrizActualizada[Fila, Columna] + "\t");
             }
             // Siguiente linea
             Console.WriteLine();
         }
         Console.WriteLine("---------------------------------------------------------------------------------------------");
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error al agregar valores en columna 4 y eliminando los valores de las [filas 1 y 2] [columna 2]: " + ex.Message);
     }
 }
Beispiel #28
0
        private void GetIndex()
        {
            int rows  = table.GetLength(0);
            int cols  = table.GetLength(1);
            int index = 0;

            for (int i = 0; i < rows; i++)
            {
                while (time[i] < t)
                {
                    index = i;
                    break;
                }
            }
            for (int i = 0; i < orderPlus1; i++)
            {
                weightFunction[i] = 1;
                if (i % 2 == 0)
                {
                    terms[i]  = time[index - i];
                    values[i] = functions[index - i];
                }
                else
                {
                    terms[i]  = time[index + 1];
                    values[i] = functions[index + 1];
                    index     = index + 1;
                }
            }
            DisplayMatrix(terms);
            Console.WriteLine();
            DisplayMatrix(values);
            Console.WriteLine();

            for (int i = 0; i < orderPlus1; i++)
            {
                WeightingFunction(i);
            }
            Console.WriteLine("Values of x: ");
            DisplayMatrix(terms);
            Console.WriteLine();
            Console.WriteLine("Values of L(x)");
            DisplayMatrix(weightFunction);

            for (int i = 0; i < orderPlus1; i++)
            {
                answers[i] = weightFunction[i] * values[i];
                answer     = answer + answers[i];
            }

            Console.WriteLine("f({0}) = {1}", t, answer);
        }
Beispiel #29
0
 public MyMatrix(Double[,] values)
 {
     Rows    = values.GetLength(0);
     Columns = values.GetLength(1);
     Matrix  = new double[Rows, Columns];
     for (int i = 0; i < Rows; i++)
     {
         for (int j = 0; j < Columns; j++)
         {
             Matrix[i, j] = values[i, j];
         }
     }
 }
        /// <summary>
        /// Cholesky algorithm for symmetric and positive definite matrix.
        /// </summary>
        /// <param name="matrix">Square, symmetric matrix.</param>
        /// <returns>Structure to access L and isspd flag.</returns>
        public CholeskyDecomposition(Double[,] matrix)
        {
            // Initialize.
            var A = (Double[, ])matrix.Clone();

            _dim = matrix.GetLength(0);
            _L   = new Double[_dim, _dim];
            _spd = matrix.GetLength(1) == _dim;

            // Main loop.
            for (var i = 0; i < _dim; i++)
            {
                var Lrowi = new Double[_dim];
                var d     = 0.0;

                for (var k = 0; k < _dim; k++)
                {
                    Lrowi[k] = _L[i, k];
                }

                for (int j = 0; j < i; j++)
                {
                    var Lrowj = new Double[_dim];
                    var s     = 0.0;

                    for (var k = 0; k < _dim; k++)
                    {
                        Lrowj[k] = _L[j, k];
                    }

                    for (var k = 0; k < j; k++)
                    {
                        s += Lrowi[k] * Lrowj[k];
                    }

                    s        = (A[i, j] - s) / _L[j, j];
                    Lrowi[j] = s;
                    d       += s * s;
                    _spd     = _spd && (A[j, i] == A[i, j]);
                }

                d        = A[i, i] - d;
                _spd     = _spd & (Math.Abs(d) > 0.0);
                _L[i, i] = Math.Sqrt(d);

                for (var k = i + 1; k < _dim; k++)
                {
                    _L[i, k] = 0.0;
                }
            }
        }
Beispiel #31
0
        //Fuzzy C-Means process thread\\
        private void fuzzycmeansprocessThread()
        {
            timer2.Start();
            BackgroundWorker b = new BackgroundWorker();
            int period = 0;
            int periodTrackbarValue = periodTrackBar.Value;
            metroPanel1.Visible = false;
            metroPanel2.Visible = false;
            metroPanel3.Visible = true;
            this.Text = "Process";
            fuzzyrfmTimerLabel.Visible = false;
            viewFuzzyBtn.Visible = false;
            viewResultBtn.Visible = false;
            winChartViewer1.Image = null;
            b.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                query = "SELECT TOP 1 * FROM [CSS].[dbo].[transaction] order by purchaseDate DESC";
                sqlConnection();
                sqlCon.Open();
                command = new SqlCommand();
                command.CommandText = query;
                command.CommandType = CommandType.Text;
                command.Connection = sqlCon;
                sa = new SqlDataAdapter(command);
                dt = new DataTable();
                sa.Fill(dt);
                dateCutOff = Convert.ToDateTime(dt.Rows[0][3]);

                query = "SELECT * FROM [CSS].[dbo].[transaction] order by [CID]";
                command.CommandText = query;
                command.CommandType = CommandType.Text;
                command.Connection = sqlCon;
                sa = new SqlDataAdapter(command);
                dt = new DataTable();
                sa.Fill(dt);

                //Customer table emptied\\
                delQuery = "delete [CSS].[DBO].customer";
                command = new SqlCommand(delQuery, sqlCon);
                command.CommandText = delQuery;
                sa = new SqlDataAdapter(command);
                command.Connection = sqlCon;
                command.ExecuteNonQuery();

                custName = new String[1];
                custID = new String[1];
                DateTime date = Convert.ToDateTime(dt.Rows[0][3]);
                Double mntry = Convert.ToInt64(dt.Rows[0][2]);
                X = new Double[dt.Rows.Count, 3];
                int frq = 1;
                int idx = 0;
                DataRow dr;
                dr = dt.Rows[0];

                //Customer data preprocessing\\
                for (int i = 0; i < periodTrackbarValue; i++)
                {
                    period += DateTime.DaysInMonth(dateCutOff.Year, dateCutOff.Month - i);
                }
                for (int i = 0; i < dt.Rows.Count - 1; i++)
                {
                    if (Convert.ToInt32((dateCutOff - Convert.ToDateTime(dr.Table.Rows[i][3])).TotalDays) <= period)
                    {
                        custName[idx] = dr.Table.Rows[i][1].ToString();
                        custID[idx] = dr.Table.Rows[i][4].ToString();
                        if (custID[idx] == dt.Rows[i + 1][4].ToString())
                        {
                            if (Convert.ToInt32((dateCutOff - Convert.ToDateTime(dt.Rows[i + 1][3])).TotalDays) <= period)
                            {
                                if (Convert.ToDateTime(dt.Rows[i + 1][3]) > Convert.ToDateTime(dr.Table.Rows[i][3]))
                                {
                                    date = Convert.ToDateTime(dt.Rows[i + 1][3]);
                                }
                                frq += 1;
                                mntry += Convert.ToInt64(dt.Rows[i + 1][2]);
                            }
                        }
                        else if (custID[idx] != dt.Rows[i + 1][4].ToString())
                        {
                            X[idx, 0] = Convert.ToInt32((dateCutOff - date).TotalDays);
                            X[idx, 1] = frq;
                            X[idx, 2] = mntry;
                            idx += 1;
                            Array.Resize(ref custName, idx + 1);
                            Array.Resize(ref custID, idx + 1);
                            frq = 1;
                            mntry = Convert.ToInt64(dt.Rows[i + 1][2]);
                            date = Convert.ToDateTime(dt.Rows[i + 1][3]);
                        }
                    }
                }
                num = Enumerable.Range(0, X.GetLength(0)).Count(i => X[i, 0] != 0);
                //Customer calculated data insertion to customer table in SQL\\
                for (int i = 0; i < num; i++)
                {
                    String customerQuery = "INSERT customer (CID, customerName, Frequency, totalPurchase, lastPurchase, clusterIndex) VALUES ('" + custID[i] + "', '" + custName[i].Replace("'", " ") + "', '" + X[i, 1] + "', '" + X[i, 2] + "', '" + dateCutOff.AddDays(-X[i, 0]) + "', '" + 0 + "')";
                    command.CommandText = customerQuery;
                    command.CommandType = CommandType.Text;
                    command.Connection = sqlCon;
                    command = new SqlCommand(customerQuery, sqlCon);
                    command.ExecuteNonQuery();
                }
                fuzzyCMeans();
            };

            b.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
            {
                this.TopMost = true;
                this.BringToFront();
                this.Focus();
                sqlCon.Open();
                timer2.Stop();
                clusterProgressBar.Visible = false;
                clusterProgressBar.Enabled = false;
                rfmprocessBtn.Visible = true;
                rfmprocessBtn.Focus();
                this.TopMost = false;
                viewFuzzyBtn.Visible = true;
                fuzzycmeansTimerLabel.Location = new Point(163, 9);
                query = "SELECT TOP 1 * FROM [CSS].[dbo].[historyIndex] order by historyID DESC";
                command.CommandText = query;
                command.CommandType = CommandType.Text;
                command.Connection = sqlCon;
                sa = new SqlDataAdapter(command);
                dt = new DataTable();
                sa.Fill(dt);
                query = "UPDATE [CSS].[dbo].historyIndex set fuzzyProcessTime ='" + timeSpan + "', MPCScore='" + MPCScore + "', fuzzyRFMTime=null where historyID ='" + dt.Rows[0][0].ToString() + "'";
                command.CommandText = query;
                command.CommandType = CommandType.Text;
                command.Connection = sqlCon;
                command.ExecuteNonQuery();
                sqlCon.Close();
            };
            clusterProgressBar.Enabled = true;
            b.RunWorkerAsync();
        }