matrix, sub matrix with greatest sum - c#

The task:
1. Make a matrix n by m and fill it with data from console.
2. Find the 3*3 sub matrix with the greatest sum.
{
static int[,] ArrayReadConsole()
{
Console.WriteLine("please enter n:");
int n;
n = Int32.Parse(Console.ReadLine());
Console.WriteLine("please enter m:");
int m;
m = Int32.Parse(Console.ReadLine());
int[,] data = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
Console.WriteLine("please enter a new value");
int number;
number = Int32.Parse(Console.ReadLine());
data[i, j] = number;
}
}
return data;
}
static void SumOfPlatform(int[,] data)
{
int sum =0;
int x = 0;
int y = 0;
int maxSum = 0;
for (int i = 0; i < data.GetLength(0) - 2; i++)
{
for (int j = 0; j < data.GetLength(1) - 2; j++)
{
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
sum =+ data[i + k, j + l];
}
}
if (maxSum < sum)
{
maxSum = sum;
x = i;
y = j;
}
sum =0;
}
}
Console.WriteLine("Sum: {0}\nPosition: {1} {2}",maxSum,x,y );
}
static void Main()
{
int[,] data = ArrayReadConsole();
SumOfPlatform(data);
}
}
}
I wrote that code but something went wrong... It doesn't find position or sum of the matrix I enter. I know that 4x for loop is a bad idea just I didn't want to make another method just for that. Any idea why it doesn't work?

Your Code for SumOfPlatform is working with only change from =+ to +=
static void SumOfPlatform(int[,] data)
{
int sum = 0;
int x = 0;
int y = 0;
int maxSum = 0;
for (int i = 0; i < data.GetLength(0) - 2; i++)
{
for (int j = 0; j < data.GetLength(1) - 2; j++)
{
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
sum += data[i + k, j + l]; //only Change
}
}
if (maxSum < sum)
{
maxSum = sum;
x = i;
y = j;
}
sum = 0;
}
}
Console.WriteLine("Sum: {0}\nPosition: {1} {2}", maxSum, x, y);
}
static void Main(string[] args)
{
// int[,] data = ArrayReadConsole();
int[,] data = new int[,]
{
{1,4,6,7,3,5,7,4 },
{1,4,5,3,3,5,4,4 },
{1,1,6,2,1,5,7,4 },
{1,3,6,3,3,5,2,4 },
{1,4,6,2,3,5,3,4 },
{1,4,2,2,3,5,3,4 },
{1,4,3,3,3,5,2,4 },
{1,4,4,3,3,5,2,4 }
};
SumOfPlatform(data);
}

Related

How to write recursive function for nested loops in C#

How can I write recursive function for this for loops I am making sum of this array elements.
int[,,,] exampleArray = new int[1,2,3,4];
int sum = 0;
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 4; l++)
{
sum += exampleArray[i, j, k, l];
}
}
}
}
Console.WriteLine(sum);
it is actually quite simple, just need a way to represent all 4 indexes as single variable:
static int recursiveSum(int[,,,] a, int index = 0)
{
int ti = index;
int l = ti % a.GetLength(3); ti /= a.GetLength(3);
int k = ti % a.GetLength(2); ti /= a.GetLength(2);
int j = ti % a.GetLength(1); ti /= a.GetLength(1);
int i = ti % a.GetLength(0); ti /= a.GetLength(0);
if (ti > 0) {
return 0;
}
return a[i, j, k, l] + recursiveSum(a, index + 1);
}
static void Main(string[] args)
{
int[,,,] exampleArray = new int[1, 2, 3, 4];
int sum = recursiveSum(exampleArray);
Console.WriteLine(sum);
}

Multiplication matrix on vector

I need to multiply the matrix on the vector and print the result. There are classes of integer vector and integer matrix. When outputting, displays only the first element. Can you tell me what the error is? Below I show the overloading of the * operator that I made, the method for displaying the matrix and exactly how I display it. Here is an example
public class VectorInt//class VectorInt
{
protected int[] IntArray;
protected uint size;
protected int codeError;
protected static uint num_vec;
public VectorInt()
{
codeError = 1;
size = 1;
IntArray = new int[size];
IntArray[0] = 0;
num_vec++;
}
public VectorInt(uint n)//конструктор з одним параметром
{
codeError = 1;
size = n;
IntArray = new int[size];
for (int i = 0; i < n; i++)
{
IntArray[i] = 0;
}
num_vec++;
}
public VectorInt(uint n, int b)
{
codeError = 1;
size = n;
IntArray = new int[size];
for (int i = 0; i < n; i++)
{
IntArray[i] = b;
}
num_vec++;
}
~VectorInt()
{
num_vec--;
Console.WriteLine("Dipsosed");
}
public void Input()
{
Console.WriteLine("\nSize of vector: ");
size = uint.Parse(Console.ReadLine());
IntArray = new int[size];
for (int i = 0; i < size; i++)
{
Console.WriteLine("Element {0}: ", i);
Console.WriteLine(" v [ {0} ] = {1} ", i, IntArray[i] = int.Parse(Console.ReadLine()));
}
}
public void Output()
{
Console.WriteLine("\nMatrix");
for (int i = 0; i < n; i++)//n-amount of rows
{
for (int j = 0; j < m; j++)//m-amount of columns
{
Console.Write(" m [ {0}{1} ] = {2} ", i, j, IntArray[i, j]);
}
Console.WriteLine();
}
}
public uint Size
{
get
{
return (uint)IntArray.Length;
}
}
public int[] NewIntArray
{
get => IntArray;
}
////////////////////////////////////////////////////////
public class MatrixInt//class MatrixInt
{
protected int[,] IntArray;
protected int n, m;
protected int codeError;
protected static int num_m;
public MatrixInt()
{
n = 1; m = 1;
IntArray = new int[n, m];
IntArray[0, 0] = 0;
num_m++;
}
public MatrixInt(int r, int c)
{
n = r; m = c;
IntArray = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
IntArray[i, j] = 0;
}
num_m++;
}
public MatrixInt(int r, int c, int b)
{
n = r; m = c;
IntArray = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
IntArray[i, j] = b;
}
num_m++;
}
~MatrixInt()
{
num_m--;
Console.WriteLine("Disposed");
}
public void Input()
{
Console.WriteLine("Number of rows: ");
n = int.Parse(Console.ReadLine());
Console.WriteLine("Number of columns: ");
m = int.Parse(Console.ReadLine());
IntArray = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
Console.WriteLine("Element {0}{1}: ", i, j);
Console.WriteLine(" m [ {0}{1} ] = {2} ", i, j, IntArray[i, j] = int.Parse(Console.ReadLine()));
}
}
}
public void Output()
{
Console.WriteLine("\nMatrix");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
Console.Write(" m [ {0}{1} ] = {2} ", i, j, IntArray[i, j]);
}
Console.WriteLine();
}
}
public int Rows
{
get
{
return n;
}
}
public int Columns
{
get
{
return m;
}
}
/////////////////////////////////////////////////////////////
public static MatrixInt operator *(MatrixInt obj, VectorInt obj1)
{
MatrixInt obj3 = new MatrixInt();
if (obj.Columns != obj1.NewIntArray.Length)
{
throw new Exception("Error!");
}
obj3.IntArray = new int[obj.Rows, 1];
for (int i = 0; i < obj.Rows; i++)
{
obj3.IntArray[i, 0] = 0;
for (int j = 0; j < obj.Columns; j++)
{
obj3.IntArray[i, 0] += obj.IntArray[i, j] * obj1.NewIntArray[j];
//Console.WriteLine(" m [ {0}{1} ] = {2} ", i, j, obj3.IntArray[i, 0]);
}
}
return obj3;
}
////////////////////////////////////////////////////////
MatrixInt obj = new MatrixInt();
VectorInt obj1 = new VectorInt();
obj.Input();
obj.Output();
obj1.Input();
obj1.Output();
obj *= obj1;
obj.Output();

Check common elements of two-dimensional arrays of integers, considering the positions they are on

at the beginning I want to mention that I am a beginner in programming. So, I want to write a program that checks the similarity of two-dimensional arrays of integers. The similarity is to be determined by the amount of numbers that are in the same positions in both tables. The user gives the number of columns in the table and the elements themselves, number of rows is the same all the time.The similarity result is displayed as a percentage and the similarity itself should be calculated taking into account the number of elements of the larger array. My problem is: When the two arrays are the same size, the program throws the exception and it doesn't check all the numbers in the column.(I wrote before program for one dimensional array and it works perfectly) So far I have managed to write something like this:
This is what I want to do In the picture, the similarity between the arrays is 20%
{
Console.WriteLine("How extensive is the first table supposed to be?");
int n = int.Parse(Console.ReadLine());
int z = 2;
int[,] tab1 = new int[2, n];
Console.WriteLine("Enter the numbers into the first array:");
for (int i = 0; i < z; i++)
{
for (int j = 0; j < n; j++)
{
tab1[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\n");
int rowLength = tab1.GetLength(0);
int colLength = tab1.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", tab1[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine("How extensive is the second table supposed to be?");
int m = int.Parse(Console.ReadLine());
int b = 2;
int[,] tab2 = new int[2, m];
Console.WriteLine("Enter the numbers into the second array: ");
for (int i = 0; i < b; i++)
{
for (int j = 0; j < m; j++)
{
tab2[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\n");
int Len4gth = tab2.GetLength(0);
int Len2gth = tab2.GetLength(1);
for (int i = 0; i < Len4gth; i++)
{
for (int j = 0; j < Len2gth; j++)
{
Console.Write(string.Format("{0} ", tab2[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
double similarity= 0;
if (tab1.GetLength(1) > tab2.GetLength(1))
{
for (int i = 0; i < tab2.GetLength(1); i++)
{
for (int j = 0; j < z; j++)
{
if (tab1[i, j] == tab2[i, j])
{
similarity+= 1;
}
}
}
}
if (tab1.GetLength(1) < tab2.GetLength(1))
{
for (int i = 0; i < tab1.GetLength(1); i++)
{
for (int j = 0; j < z; j++)
{
if (tab2[i, j] == tab1[i, j])
{
similarity+= 1;
}
}
}
}
if (tab1.GetLength(1) == tab2.GetLength(1))
{
for (int i = 0; i < tab1.GetLength(1); i++)
{
for (int j = 0; j < z; j++)
{
if (tab1[i, j] == tab2[i, j])
{
similarity+= 1;
}
}
}
}
if (tab1.Length < tab2.Length)
{
Console.WriteLine("The similarity of the arrays is: " + (similarity/ tab2.Length) * 100 + "%");
}
if (tab1.Length > tab2.Length)
{
Console.WriteLine("The similarity of the arrays is: " + (similarity/ tab1.Length) * 100 + "%");
}
if (tab1.Length == tab2.Length)
{
Console.WriteLine("The similarity of the arrays is: " + (similarity/ tab2.Length) * 100 + "%");
}
Console.ReadKey();
You must compare each element of the first array with the elements of the second array.
use this code :
//get first array items
Console.WriteLine("How extensive is the first table supposed to be?");
int n = int.Parse(Console.ReadLine());
int[,] tab1 = new int[2, n];
Console.WriteLine("Enter the numbers into the first array:");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < n; j++)
{
tab1[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\n");
//write first array items
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(string.Format("{0} ", tab1[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
//get second array items
Console.WriteLine("How extensive is the second table supposed to be?");
int m = int.Parse(Console.ReadLine());
int[,] tab2 = new int[2, m];
Console.WriteLine("Enter the numbers into the second array: ");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < m; j++)
{
tab2[i, j] = int.Parse(Console.ReadLine());
}
}
//write second array items
Console.WriteLine("\n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < m; j++)
{
Console.Write(string.Format("{0} ", tab2[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
//find similarity items
double similarity = 0;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < n; j++)
{
int firstValue = tab1[i, j];
for (int k = 0; k < 2; k++)
{
for (int d = 0; d < m; d++)
{
if (firstValue == tab2[k, d])
{
similarity += 1;
}
}
}
}
}
double percentage = n > m ? ((similarity / tab1.Length) * 100) : ((similarity / tab2.Length) * 100);
Console.WriteLine("The similarity of the arrays is: " + percentage + "%");
Console.ReadKey();
this code work without error and It does not matter which array is larger.
If you want similar elements like this example enter link description here, use this code snippet to find similar elements
//find similarity items
double similarity = 0;
int z = n > m ? m : n;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < z; j++)
{
if (tab1[i, j] == tab2[i, j])
{
similarity += 1;
}
}
}
double percentage = n > m ? ((similarity / tab1.Length) * 100) : ((similarity / tab2.Length) * 100);
Console.WriteLine("The similarity of the arrays is: " + percentage + "%");
Console.ReadKey();

How to get all possible 2x2 sub matrices in a 3x3 matrix in C#?

If matrix A of size (3x3), then should i use the method of finding determinants, like grabbing the rows and column of first element and removing it from the array 2D array to get the remaining elements and then moving to the next element and repeating the same steps ?
[{1,2,3},
{4,5,6},
{7,8,9}]
I finally was able to do it, here's what I did :
enter image description here
class program
{
public static void Main()
{
int[,] arr = new int[3, 3];
Console.WriteLine("Enter elements of " + (arr.GetUpperBound(0) + 1) + "x" + (arr.GetUpperBound(1) + 1) + " matrix:");
for (int i = 0; i < (arr.GetUpperBound(0) + 1); i++)
{
for (int j = 0; j < (arr.GetUpperBound(1) + 1); j++)
{
arr[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Matrix entered: ");
for (int i = 0; i < (arr.GetUpperBound(0) + 1); i++)
{
for (int j = 0; j < (arr.GetUpperBound(1) + 1); j++)
{
Console.Write("\t" + arr[i, j]);
}
Console.WriteLine();
}
Console.WriteLine("Possible sub-matrices: ");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j< 3; j++)
{
TrimArray(i,j,arr);
}
}
}
public static int[,] TrimArray(int row, int column, int[,] original)
{
int[,] resultant = new int[original.GetLength(0) - 1, original.GetLength(1) - 1];
for (int i = 0, j = 0; i < original.GetLength(0); i++)
{
if (i == row)
continue;
for (int k = 0, u = 0; k < original.GetLength(1); k++)
{
if (k == column)
continue;
resultant[j, u] = original[i, k];
u++;
}
j++;
}
Console.WriteLine();
for (int i = 0; i < 2; i++)
{
for (int j = 0; j< 2; j++)
{
Console.Write("\t"+resultant[i,j]);
}
Console.WriteLine();
}
return resultant;
}
}
I did this for you yesterday, I created a method that will return a square matrix, given a parent matrix and the length.
static void Main(string[] args)
{
int[][] parentMatrix = new int[][]
{
new int [] { 1, 2, 3 },
new int [] { 4, 5, 6 },
new int [] { 7, 8, 9 }
};
var chunks = GetSubMatrices(parentMatrix, 2);
Console.WriteLine(chunks);
}
static List<int[][]> GetSubMatrices(int[][] parentMatrix, int m)
{
int n = parentMatrix.Length > m ? parentMatrix.Length : throw new InvalidOperationException("You can't use a matrix smaller than the chunk size");
var chunks = new List<int[][]>();
int movLimit = n - m + 1;
var allCount = Math.Pow(movLimit, 2);
for (int selRow = 0; selRow < movLimit; selRow ++)
{
for (int selCol = 0; selCol < movLimit; selCol ++)
{
// this is start position of the chunk
var chunk = new int[m][];
for (int row = 0; row < m; row++)
{
chunk[row] = new int[m];
for (int col = 0; col < m; col++)
{
chunk[row][col] = parentMatrix[selRow + row][selCol + col];
}
}
chunks.Add(chunk);
}
}
return chunks;
}
If you have any problems using it, you can simply comment below.
I needed to solve a problem like and came up with this answer. Hope it adds to your library of answers. If the submatrix specified is not greater than 1, do nothing.
public static void GetSubMatrixes(int[,] arr, int size)
{
int parentMatrixRowLength = arr.GetLength(0);
int parentMatrixColLength = arr.GetLength(1);
var overall = new List<object>();
if(size > 1)
{
for (int i = 0; i < parentMatrixRowLength; i++)
{
//get the columns
for (int j = 0; j < parentMatrixColLength; j++)
{
var subMatrix = new int[size, size];
/*if the new matrix starts from second to the last value in either the row(horizontal or column)
* do not proceed, go to the row or column in the parent matrix
* */
if (j < parentMatrixColLength - (size - 1) && i < parentMatrixRowLength - (size - 1))
{
//add
for (int m = 0; m < subMatrix.GetLength(0); m++)
{
for (int n = 0; n < subMatrix.GetLength(1); n++)
{
/*check the sum of current column value and the sum of the current row value
* of the parent column length and row length if it goes out of bounds
*/
var row = i + m; var col = j + n;
//actual check here
if (row < parentMatrixRowLength && col < parentMatrixColLength)
{
subMatrix[m, n] = arr[i + m, j + n];
}
}
}
overall.Add(subMatrix);
}
}
}
//display the sub matrixes here
for (int i = 0; i < overall.Count; i++)
{
var matrix = overall[i] as int[,];
for (int y = 0; y < matrix.GetLength(0); y++)
{
for (int x = 0; x < matrix.GetLength(1); x++)
{
Console.Write(string.Format("{0} ", matrix[y, x]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine();
}
}
}

How to invert double[,] in C#

I am making a program, where I need to calculate linear regression, but I got stuck at inversion of a matrix.
I have
double[,] location = new double[3,3];
It was then filled with numbers, but then I do not know, how to count the inverse matrix for it like in Linear algebra.
I searched for a solution on the internet, but there was some Matrix class that I dont know how to convert my double[,] to.
So, do you know some elegant way to inverse double[,] like the inversion of matrixes in Linear algebra?
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/
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;
}
}
}
I guess this is what you are looking for:
static double[][] MatrixInverse(double[][] matrix)
{
// assumes determinant is not 0
// that is, the matrix does have an inverse
int n = matrix.Length;
double[][] result = MatrixCreate(n, n); // make a copy of matrix
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
result[i][j] = matrix[i][j];
double[][] lum; // combined lower & upper
int[] perm;
int toggle;
toggle = MatrixDecompose(matrix, out lum, out perm);
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 = Helper(lum, b); //
for (int j = 0; j < n; ++j)
result[j][i] = x[j];
}
return result;
}
See Test Run - Matrix Inversion Using C# for reference.

Categories