logo
down
shadow

Double[,], inversion C#


Double[,], inversion C#

By : Alex Vohs
Date : November 19 2020, 03:01 PM
hop of those help? Here you have a working example, just copy the entire code into a console project and run it. I took it from this link https://jamesmccaffrey.wordpress.com/2015/03/06/inverting-a-matrix-using-c/
code :
 using System;
using System.Collections.Generic;
using System.Linq;




namespace matrixExample
{

    class Program
    {

        static void Main(string[] args)
        {

            double[][] m = new double[][] { new double[] { 7, 2, 1 }, new double[] { 0, 3, -1 }, new double[] { -3, 4, 2 } };
            double[][] inv = MatrixInverse(m);


            //printing the inverse
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                    Console.Write(Math.Round(inv[i][j], 1).ToString().PadLeft(5, ' ') + "|");
                Console.WriteLine();
            }

        }

        static double[][] MatrixCreate(int rows, int cols)
        {
            double[][] result = new double[rows][];
            for (int i = 0; i < rows; ++i)
            result[i] = new double[cols];
            return result;
        }

        static double[][] MatrixIdentity(int n)
        {
            // return an n x n Identity matrix
            double[][] result = MatrixCreate(n, n);
            for (int i = 0; i < n; ++i)
            result[i][i] = 1.0;

            return result;
        }

        static double[][] MatrixProduct(double[][] matrixA, double[][] matrixB)
        {
            int aRows = matrixA.Length; int aCols = matrixA[0].Length;
            int bRows = matrixB.Length; int bCols = matrixB[0].Length;
            if (aCols != bRows)
                throw new Exception("Non-conformable matrices in MatrixProduct");

            double[][] result = MatrixCreate(aRows, bCols);

            for (int i = 0; i < aRows; ++i) // each row of A
                for (int j = 0; j < bCols; ++j) // each col of B
                      for (int k = 0; k < aCols; ++k) // could use k less-than bRows
                        result[i][j] += matrixA[i][k] * matrixB[k][j];

            return result;
        }

        static double[][] MatrixInverse(double[][] matrix)
        {
            int n = matrix.Length;
            double[][] result = MatrixDuplicate(matrix);

            int[] perm;
            int toggle;
            double[][] lum = MatrixDecompose(matrix, out perm,
              out toggle);
            if (lum == null)
                throw new Exception("Unable to compute inverse");

            double[] b = new double[n];
            for (int i = 0; i < n; ++i)
      {
                for (int j = 0; j < n; ++j)
        {
                    if (i == perm[j])
                        b[j] = 1.0;
                    else
                        b[j] = 0.0;
                }

                double[] x = HelperSolve(lum, b);

                for (int j = 0; j < n; ++j)
          result[j][i] = x[j];
            }
            return result;
        }

        static double[][] MatrixDuplicate(double[][] matrix)
        {
            // allocates/creates a duplicate of a matrix.
            double[][] result = MatrixCreate(matrix.Length, matrix[0].Length);
            for (int i = 0; i < matrix.Length; ++i) // copy the values
                for (int j = 0; j < matrix[i].Length; ++j)
                    result[i][j] = matrix[i][j];
            return result;
        }

        static double[] HelperSolve(double[][] luMatrix, double[] b)
        {
            // before calling this helper, permute b using the perm array
            // from MatrixDecompose that generated luMatrix
            int n = luMatrix.Length;
            double[] x = new double[n];
            b.CopyTo(x, 0);

            for (int i = 1; i < n; ++i)
            {
                double sum = x[i];
                for (int j = 0; j < i; ++j)
                    sum -= luMatrix[i][j] * x[j];
                x[i] = sum;
            }

            x[n - 1] /= luMatrix[n - 1][n - 1];
            for (int i = n - 2; i >= 0; --i)
            {
                double sum = x[i];
                for (int j = i + 1; j < n; ++j)
                    sum -= luMatrix[i][j] * x[j];
                x[i] = sum / luMatrix[i][i];
            }

            return x;
        }

        static double[][] MatrixDecompose(double[][] matrix, out int[] perm, out int toggle)
        {
            // Doolittle LUP decomposition with partial pivoting.
            // rerturns: result is L (with 1s on diagonal) and U;
            // perm holds row permutations; toggle is +1 or -1 (even or odd)
            int rows = matrix.Length;
            int cols = matrix[0].Length; // assume square
            if (rows != cols)
                throw new Exception("Attempt to decompose a non-square m");

            int n = rows; // convenience

            double[][] result = MatrixDuplicate(matrix);

            perm = new int[n]; // set up row permutation result
            for (int i = 0; i < n; ++i) { perm[i] = i; }

            toggle = 1; // toggle tracks row swaps.
                        // +1 -greater-than even, -1 -greater-than odd. used by MatrixDeterminant

            for (int j = 0; j < n - 1; ++j) // each column
            {
                double colMax = Math.Abs(result[j][j]); // find largest val in col
                int pRow = j;
                //for (int i = j + 1; i less-than n; ++i)
                //{
                //  if (result[i][j] greater-than colMax)
                //  {
                //    colMax = result[i][j];
                //    pRow = i;
                //  }
                //}

                // reader Matt V needed this:
                for (int i = j + 1; i < n; ++i)
                {
                    if (Math.Abs(result[i][j]) > colMax)
                    {
                        colMax = Math.Abs(result[i][j]);
                        pRow = i;
                    }
                }
                // Not sure if this approach is needed always, or not.

                if (pRow != j) // if largest value not on pivot, swap rows
                {
                    double[] rowPtr = result[pRow];
                    result[pRow] = result[j];
                    result[j] = rowPtr;

                    int tmp = perm[pRow]; // and swap perm info
                    perm[pRow] = perm[j];
                    perm[j] = tmp;

                    toggle = -toggle; // adjust the row-swap toggle
                }

                // --------------------------------------------------
                // This part added later (not in original)
                // and replaces the 'return null' below.
                // if there is a 0 on the diagonal, find a good row
                // from i = j+1 down that doesn't have
                // a 0 in column j, and swap that good row with row j
                // --------------------------------------------------

                if (result[j][j] == 0.0)
                {
                    // find a good row to swap
                    int goodRow = -1;
                    for (int row = j + 1; row < n; ++row)
                    {
                        if (result[row][j] != 0.0)
                            goodRow = row;
                    }

                    if (goodRow == -1)
                        throw new Exception("Cannot use Doolittle's method");

                    // swap rows so 0.0 no longer on diagonal
                    double[] rowPtr = result[goodRow];
                    result[goodRow] = result[j];
                    result[j] = rowPtr;

                    int tmp = perm[goodRow]; // and swap perm info
                    perm[goodRow] = perm[j];
                    perm[j] = tmp;

                    toggle = -toggle; // adjust the row-swap toggle
                }
                // --------------------------------------------------
                // if diagonal after swap is zero . .
                //if (Math.Abs(result[j][j]) less-than 1.0E-20) 
                //  return null; // consider a throw

                for (int i = j + 1; i < n; ++i)
                {
                    result[i][j] /= result[j][j];
                    for (int k = j + 1; k < n; ++k)
                    {
                        result[i][k] -= result[i][j] * result[j][k];
                    }
                }


            } // main j column loop

            return result;
        }




    }
}


Share : facebook icon twitter icon
Events in an Inversion of Control (Dependency Inversion) system go which way?

Events in an Inversion of Control (Dependency Inversion) system go which way?


By : Ahmer Jamil
Date : March 29 2020, 07:55 AM
With these it helps For the sake of brevity, I'm going to refer to the objects contained within the container as "client objects" or just "clients"...
Events can legitimately flow in both directions without introducing unwanted dependencies between the container and the clients. In fact, allowing the container to receive events from the clients is a great way to minimize these dependencies. They provide a path for loose coupling precisely so that the container will be able to remain ignorant of what the clients actually are while still communicating with them. As long as the events in question are defined by the container, not by the clients.
Develop layers first having in mind transition to Dependency Inversion principle and Inversion of Control at a later sta

Develop layers first having in mind transition to Dependency Inversion principle and Inversion of Control at a later sta


By : Suresh Kumar Mukhiya
Date : March 29 2020, 07:55 AM
hope this fix your issue You can set up "poor man's dependency injection", using this kind of structure:
code :
public class MyEndClass
{
    private readonly IDependency dependency;

    public MyEndClass(IDependency dependency)
    {
        this.dependency = dependency;
    }

    // temporary constructor until we introduce IoC
    public MyEndClass() : this(new Dependency())
    {
    }
}
Inversion of Control, Dependency Inversion, and Service Locator difference clarification

Inversion of Control, Dependency Inversion, and Service Locator difference clarification


By : CANZ
Date : March 29 2020, 07:55 AM
I hope this helps . Yes, you are correct.
SL is typically used inside frameworks to be able to locate all services. From the developers point of view they are just using dependency injection as the framework hides the service location. A typical example is ASP.NET MVC where you can use DI in your controllers. ASP.NET uses service location internally through the DependencyResolver class to allow you to use DI.
Object is not null and not undefined. What is better - double inversion `!!` or strict equillity `!==` in JavaScript

Object is not null and not undefined. What is better - double inversion `!!` or strict equillity `!==` in JavaScript


By : lang
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further There isn’t any particularly good reason to ever use if (!!obj), as it’s equivalent to if (obj). !!obj and obj !== null && obj !== undefined do different things, though, and you should use whichever’s most appropriate.
obj !== null && obj !== undefined (surprise, surprise) results in false for null and undefined. !!obj results in false for anything falsy, including null, undefined, '', 0, NaN, and false.
double values closed under inversion

double values closed under inversion


By : sukhdev roy
Date : March 29 2020, 07:55 AM
it should still fix some issue using bisection search, I found the interval of double values that is invariant under 2x inversion
code :
value == 1.0 / (1.0 / value)
[5.562684646268010E-309 ... 1.7976931348623151E308]
Related Posts Related Posts :
  • Access class item generated from xml using xsd.exe
  • Is there a shortcut to explicit named paramers when I call a method in C# for VisualStudio 2017?
  • Sorting datatables in a dataset with the datatable.name
  • Datagridview multilpe links
  • Correct pattern for exposing available actions
  • Local web application accepts numbers with comma and published does not
  • How to read an xml file using xmldataprovider in wpf C#
  • Windows service and Entity Framework
  • Visual Studio 2017 Docker support not available for ASP.Net Core Angular or React projects
  • Datacontext models with join
  • WPF: Increased window size decreases performance
  • Handling bad CSV records in CsvHelper
  • C# Displays file icons in asp.net on GridView nested
  • is there a way to get the file names which need to be updated if TFS status.Numoperations != 0?
  • Headless Firefox in Selenium C#
  • How do I start a .exe with a json string as parameter correctly?
  • StreamContent not loaded to the end
  • HAP parses formatting in HTML documents
  • repeat and count a loop in an unordered sequence in C#
  • Redundant Casting in Visual studio
  • Lost references in Visual Studio 2017 solution
  • Is there a way to add two numbers using a private constructor in C#
  • Is it possible to execute multiple SSH commands from a single login session with SSH.NET?
  • How can I get NHibernate to map to a Tuple or Class?
  • MVC 5 C# Window Authentication pop up when I navigate to a certain area
  • Mongo C# driver toJson() DateTime
  • Coprime integers
  • What is the purpose with files ending with *CS.cs in Xamarin Forms projects?
  • MVC5 / Entity | Update/Create Complex Model
  • How to return auto increment ID from SQL using Petapoco ORM in .NET MVC
  • Create new web app offline c# using Visual Studio
  • How many times is ordered the IEnumerable in this case?
  • C# error when update database 2008 to sql 2016
  • How to insert string in multiple continuous pattern in windows c#
  • How to send temp data from Partial View to its parent View
  • C# encapsulation when getting updates from asynchronous method
  • Asp net core Content Security Policy implementation
  • @Html.DropDownList() Placeholder as Disable and Selected
  • Set AM/PM in Material Time Picker WPF
  • Ninject passing reference in constructor
  • C# Entity Framework text SQL query wrapper
  • Core 2.0 MVC - AD Group Authorization for logging
  • Decentralized NLog Target per Http request
  • How to use x:Object and when?
  • Displays file icons in asp.net on GridView
  • How do I avoid two (or more) threads that work on a table at the same time to not work on same row?
  • Add xml attribute for property in DB First
  • How do i execute 2 sql queries by clicking a button [C#]
  • convert jsonstring to objects c#
  • How do request a correct access token in ASP.NET Core for Azure AD to access Microsoft Graph
  • How to run a .NET Core console application on Linux
  • UI not updating for bound element
  • C# Odata v4 open type raw values
  • DocumentFormat.OpenXml Modify Creator Propery of Document
  • How to SetBasePath in ConfigurationBuilder in Core 2.0
  • ASP MVC5 public readonly variable changes value when it should not
  • How to conditionally select item from hashset with queryable linq?
  • Progress Bar C# not showing the real progress
  • Correct logic to reconnect in SignalR with HubConnection
  • ComboBox with two or more sections
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org