Calculating an NxN matrix determinant in C# - c#

How do you calculate the determinant of an NxN matrix C# ?

The OP posted another question asking specifically about 4x4 matrices, which has been closed as an exact duplicate of this question. Well, if you're not looking for a general solution but instead are constrained to 4x4 matrices alone, then you can use this ugly looking but tried-and-true code:
public double GetDeterminant() {
var m = _values;
return
m[12] * m[9] * m[6] * m[3] - m[8] * m[13] * m[6] * m[3] -
m[12] * m[5] * m[10] * m[3] + m[4] * m[13] * m[10] * m[3] +
m[8] * m[5] * m[14] * m[3] - m[4] * m[9] * m[14] * m[3] -
m[12] * m[9] * m[2] * m[7] + m[8] * m[13] * m[2] * m[7] +
m[12] * m[1] * m[10] * m[7] - m[0] * m[13] * m[10] * m[7] -
m[8] * m[1] * m[14] * m[7] + m[0] * m[9] * m[14] * m[7] +
m[12] * m[5] * m[2] * m[11] - m[4] * m[13] * m[2] * m[11] -
m[12] * m[1] * m[6] * m[11] + m[0] * m[13] * m[6] * m[11] +
m[4] * m[1] * m[14] * m[11] - m[0] * m[5] * m[14] * m[11] -
m[8] * m[5] * m[2] * m[15] + m[4] * m[9] * m[2] * m[15] +
m[8] * m[1] * m[6] * m[15] - m[0] * m[9] * m[6] * m[15] -
m[4] * m[1] * m[10] * m[15] + m[0] * m[5] * m[10] * m[15];
}
It assumes you store your vector data in a 16-element array called _values (of double in this case, but float would work too), in the following order:
0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
12, 13, 14, 15

Reduce to upper triangular form, then make a nested loop where you multiply all the values at position i == j together. There you have it.

The standard method is LU decomposition. You may want to use a library instead of coding it yourself. I don't know about C#, but the 40-year standard is LAPACK.

This solution is achieved using row operations. I took an identity matrix of the same dimensions as of my target matrix and then converted the target matrix to the identity matrix such that, every operation which is performed on target matrix, must also be performed to the identity matrix. In last, the target matrix will become identity matrix and the identity matrix will hold the inverse of the target matrix.
private static double determinant(double[,] matrix, int size)
{
double[] diviser = new double[size];// this will be used to make 0 all the elements of a row except (i,i)th value.
double[] temp = new double[size]; // this will hold the modified ith row after divided by (i,i)th value.
Boolean flag = false; // this will limit the operation to be performed only when loop n != loop i
double determinant = 1;
if (varifyRowsAndColumns(matrix, size)) // verifies that no rows or columns are similar or multiple of another row or column
for (int i = 0; i < size; i++)
{
int count = 0;
//this will hold the values to be multiplied by temp matrix
double[] multiplier = new double[size - 1];
diviser[i] = matrix[i, i];
//if(i,i)th value is 0, determinant shall be 0
if (diviser[i] == 0)
{
determinant = 0;
break;
}
/*
* whole ith row will be divided by (i,i)th value and result will be stored in temp matrix.
* this will generate 1 at (i,i)th position in temp matrix i.e. ith row of matrix
*/
for (int j = 0; j < size; j++)
{
temp[j] = matrix[i, j] / diviser[i];
}
//setting up multiplier to be used for multiplying the ith row of temp matrix
for (int o = 0; o < size; o++)
if (o != i)
multiplier[count++] = matrix[o, i];
count = 0;
//for creating 0s at every other position than (i,i)th
for (int n = 0; n < size; n++)
{
for (int k = 0; k < size; k++)
{
if (n != i)
{
flag = true;
matrix[n, k] -= (temp[k] * multiplier[count]);
}
}
if (flag)
count++;
flag = false;
}
}
else determinant = 0;
//if determinant is not 0, (i,i)th element will be multiplied and the result will be determinant
if (determinant != 0)
for (int i = 0; i < size; i++)
{
determinant *= matrix[i, i];
}
return determinant;
}
private static Boolean varifyRowsAndColumns(double[,] matrix, int size)
{
List<double[]> rows = new List<double[]>();
List<double[]> columns = new List<double[]>();
for (int j = 0; j < size; j++)
{
double[] temp = new double[size];
for (int k = 0; k < size; k++)
{
temp[j] = matrix[j, k];
}
rows.Add(temp);
}
for (int j = 0; j < size; j++)
{
double[] temp = new double[size];
for (int k = 0; k < size; k++)
{
temp[j] = matrix[k, j];
}
columns.Add(temp);
}
if (!RowsAndColumnsComparison(rows, size))
return false;
if (!RowsAndColumnsComparison(columns, size))
return false;
return true;
}
private static Boolean RowsAndColumnsComparison(List<double[]> rows, int size)
{
int countEquals = 0;
int countMod = 0;
int countMod2 = 0;
for (int i = 0; i < rows.Count; i++)
{
for (int j = 0; j < rows.Count; j++)
{
if (i != j)
{
double min = returnMin(rows.ElementAt(i), rows.ElementAt(j));
double max = returnMax(rows.ElementAt(i), rows.ElementAt(j));
for (int l = 0; l < size; l++)
{
if (rows.ElementAt(i)[l] == rows.ElementAt(j)[l])
countEquals++;
for (int m = (int)min; m <= max; m++)
{
if (rows.ElementAt(i)[l] % m == 0 && rows.ElementAt(j)[l] % m == 0)
countMod++;
if (rows.ElementAt(j)[l] % m == 0 && rows.ElementAt(i)[l] % m == 0)
countMod2++;
}
}
if (countEquals == size)
{
return false;
// one row is equal to another row. determinant is zero
}
if (countMod == size)
{
return false;
}
if (countMod2 == size)
{
return false;
}
}
}
}
return true;
}
private static double returnMin(double[] row1, double[] row2)
{
double min1 = row1[0];
double min2 = row2[0];
for (int i = 1; i < row1.Length; i++)
if (min1 > row1[i])
min1 = row1[i];
for (int i = 1; i < row2.Length; i++)
if (min2 > row2[i])
min2 = row2[i];
if (min1 < min2)
return min1;
else return min2;
}
private static double returnMax(double[] col1, double[] col2)
{
double max1 = col1[0];
double max2 = col2[0];
for (int i = 1; i < col1.Length; i++)
if (max1 < col1[i])
max1 = col1[i];
for (int i = 1; i < col2.Length; i++)
if (max2 < col2[i])
max2 = col2[i];
if (max1 > max2)
return max1;
else return max2;
}

Related

Bug on a terrain generation algorithm

Long story short, the following is based on mesh generation and terrain heights
In my code everything seems to be fine. I have redone all of it and the same issue comes up, I don't know why.
All I know is that the last iteration of the Z for loop ain't giving the right height.
I could just set z-1 and have the game run on the rest of the map
but I feel that this will ruin my next phase of development and so I beg for hints on where might the issue be.
the code for the perlin noise is as follows
public static class PerlinFilter
{
public static float[] Filter(List<int> keyX, List<int> keyZ, int indexX = 0, int indexZ = 0, int sizeX = 100, int sizeZ = 100, int nOctaves = 3, float fBias = .6f)
{
float[] filtered = new float[(sizeX + 1) * (sizeZ + 1)];
for (int z = indexZ; z < sizeZ; z++)
{
for (int x = indexX; x < sizeX; x++)
{
float fNoise = 0.0f;
float fScale = 1.0f;
float fScaleAcc = 0.0f;
for (int o = 0; o < nOctaves; o++)
{
int nPitch = sizeZ >> o;
int nSampleX1 = x / nPitch * nPitch;
int nSampleZ1 = z / nPitch * nPitch;
int nSampleX2 = (nSampleX1 + nPitch) % sizeX;
int nSampleZ2 = (nSampleZ1 + nPitch) % sizeX;
float fBlendX = (float)(x - nSampleX1) / nPitch;
float fBlendZ = (float)(z - nSampleZ1) / nPitch;
float fSampleT = (1.0f - fBlendX) * keyX[nSampleZ1 * sizeX + nSampleX1] + fBlendX * keyZ[nSampleZ1 * sizeZ + nSampleX2];
float fSampleB = (1.0f - fBlendX) * keyX[nSampleZ2 * sizeX + nSampleX1] + fBlendX * keyZ[nSampleZ2 * sizeZ + nSampleX2];
fNoise += (fBlendZ * (fSampleB - fSampleT) + fSampleT) * fScale;
fScaleAcc += fScale;
fScale /= fBias;
}
filtered[z * sizeX + x] = fNoise / fScaleAcc;
}
}
return filtered;
}
}
and the code for the mesh is as follows:
void Generate(bool flat)
{
vertices = new Vector3[(x + 1) * (z + 1)];
for (int i = 0, iz = 0; iz <= z; iz++)
{
for (int ix = 0; ix <= x; ix++, i++)
{
if (flat)
vertices[i] = new Vector3(ix, 0, iz);
else
vertices[i] = new Vector3(ix, PerlinHeight(ix, iz), iz);
}
}
triangles = new int[x * z * 6];
for (int tris = 0, vert = 0, iz = 0; iz < z; iz++, vert++)
{
for (int ix = 0; ix < x; ix++, vert++, tris += 6)
{
triangles[tris + 0] = vert + 0;
triangles[tris + 1] = vert + x + 1;
triangles[tris + 2] = vert + 1;
triangles[tris + 3] = vert + 1;
triangles[tris + 4] = vert + x + 1;
triangles[tris + 5] = vert + x + 2;
}
}
}
public int PerlinHeight(int _x, int _z) => (int)(keyPerlin[_z * x + _x] * 1f);
keyPerlin is the result of the PerlinFilter.Filter.
If it becomes obvious that I need to add more code here let me know, this was done a few months ago, and I have been working on other parts of the game while accepting the z-1 workaround, but at this point I really need to sort this issue out.
In your noise filter generation you do
float[] filtered = new float[(sizeX + 1) * (sizeZ + 1)];
for (int z = indexZ; z < sizeZ; z++)
{
for (int x = indexX; x < sizeX; x++)
{
...
=> You don't fill the complete array with valid values! The last row for z== SizeZ and x==SizeX keeps the default value 0.
While in the mesh you do
vertices = new Vector3[(x + 1) * (z + 1)];
for (int i = 0, iz = 0; iz <= z; iz++)
{
for (int ix = 0; ix <= x; ix++, i++)
{
...
=> You set the last row of vertices all to 0.

diagonals in a rectangle of asterisks

I'm trying to print a rectangle of asterisks with its diagonals.
I have the code for it, but I'm wondering if there's any way to make it more symmetrical?
int height = int.Parse(Console.ReadLine());
int width = int.Parse(Console.ReadLine());
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (i == 0 || j == 0 || i == height - 1 || j == width - 1 || i == j || i + j == width- 1) {
Console.Write("*");
}
else {
Console.Write(" ");
}
}
Console.WriteLine();
}
With an imput of (12, 16) it comes out:
****************
** **
* * * *
* * * *
* * * *
* * * *
* * * *
* ** *
* ** *
* * * *
* * * *
****************
To draw a diagonal in a height * width rectangle:
int height = int.Parse(Console.ReadLine());
int width = int.Parse(Console.ReadLine());
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
// Calculate the slope
int x = (int) (0.5 + (1.0 * (i) * width) / (height-0.5));
if (i == 0 || j == 0 || i == height - 1 || j == width - 1 || x == j || j == width - x - 1) {
Console.Write("*");
}
else {
Console.Write(" ");
}
}
Console.WriteLine();
}

Hollow isosceles triangle # Console

There are a lot of examples to create a triangle in C#
but now i need a hollow one here fore there are a lot of examples in C or C++ but i need one in C# console , can some body give me a few examples
*
* * *
* * * *
* * * * *
* * * * * *
int i, j;
for (i = 0; i < 5; i++)
{
for (j = 5 - i; j > 0; j--)
Console.Write(" ");
for (j = 0; j <= 2 * i; j++)
Console.Write("*");
Console.WriteLine();
}
*
* *
* *
* *
* * * * * *
This Works...But if the value is greater than that s printable on a single line it breaks into next line. The maximum possible value without line break is 40. Till 40 it works well and good in my system. For larger values you have to increase the width of command prompt. It can be done using commands or by changing the width in properties of command prompt.
int i, j,n=5;
for (i = 0; i < n; i++)
{
for (j = n - i; j > 0; j--)
Console.Write(" ");
for (j = 0; j <= 2 * i; j++)
{
if (j < 2 * i && j > 0&&i!=(n-1))
Console.Write(" ");
else
Console.Write("*");
}
Console.WriteLine();
}
Try this:
void Main()
{
Int32 totalLines = 9;
for (Int32 i = 0; i <= totalLines; ++i)
Console.WriteLine(Line(i, totalLines));
}
String Line(Int32 i, Int32 totalLines)
{
Int32 charCount = 2 * totalLines + 1;
Int32 center = charCount / 2;
// Last line is filled completely
if (i == totalLines) return new String(Enumerable.Repeat('*', charCount).ToArray());
Char[] chars = Enumerable.Repeat(' ', charCount).ToArray();
chars[center-i] = '*';
chars[center+i] = '*';
return new String(chars);
}
This will only work with monospace fonts.

Sobel image processing

My algorithm output is wrong. I tried many solutions, but nothing comes out.
View my result.
SourceImage
I'm sorry Lena
for (int x = 1; x < fimage.Bitmap.Width - 1; x++)
{
for (int y = 1; y < fimage.Bitmap.Height - 1; y++)
{
double sumX = 0, sumY = 0, sum = 0;
for ( int i = -1; i <= 1; i++ )
{
for ( int j = -1; j <= 1; j++ )
{
sumX += fimage[y + i, x + j].R * kernel1[i + 1, j + 1];
sumY += fimage[y + i, x + j].R * kernel2[i + 1, j + 1];
}
}
sum = Math.Sqrt(sumX * sumX + sumY * sumY);
sum = sum > 255 ? 255 : sum < 0 ? 0 : sum;
fimage[x, y] = Color.FromArgb((byte)sum, (byte)sum, (byte)sum);
}
}
Two things that are fishy:
for ( int j = -1; j <= 1; j++ )
{
sumX += fimage[y + i, x + j].R * kernel1[i + 1, j + 1];
sumY += fimage[y + i, x + j].R * kernel2[i + 1, j + 1];
}
You only respect the red component of the image here, why is that?
The other major thing is changing the input picture while iterating through it:
sum = Math.Sqrt(sumX * sumX + sumY * sumY);
sum = sum > 255 ? 255 : sum < 0 ? 0 : sum;
fimage[x, y] = Color.FromArgb((byte)sum, (byte)sum, (byte)sum);
You should save the value to a different output image (create a new Bitmap(fimage.Width, fimage.Height) with the dimensions from the source image). That could explain the weird diagonal symmetry in your picture, where there's basically a symteric copy of the other side.

iPhone: Converting C# code to Objective-C

Can you guys help me converting this C# code to Objective-C?
I don't have a clue about C#/Visual Studio!
public static class BezierSpline
{
public static void GetCurveControlPoints(Point[] knots,
out Point[] firstControlPoints, out Point[] secondControlPoints)
{
int n = knots.Length - 1;
// Calculate first Bezier control points
// Right hand side vector
double[] rhs = new double[n];
// Set right hand side X values
for (int i = 1; i < n - 1; ++i)
rhs[i] = 4 * knots[i].X + 2 * knots[i + 1].X;
rhs[0] = knots[0].X + 2 * knots[1].X;
rhs[n - 1] = (8 * knots[n - 1].X + knots[n].X) / 2.0;
// Get first control points X-values
double[] x = GetFirstControlPoints(rhs);
// Set right hand side Y values
for (int i = 1; i < n - 1; ++i)
rhs[i] = 4 * knots[i].Y + 2 * knots[i + 1].Y;
rhs[0] = knots[0].Y + 2 * knots[1].Y;
rhs[n - 1] = (8 * knots[n - 1].Y + knots[n].Y) / 2.0;
// Get first control points Y-values
double[] y = GetFirstControlPoints(rhs);
// Fill output arrays.
firstControlPoints = new Point[n];
secondControlPoints = new Point[n];
for (int i = 0; i < n; ++i)
{
// First control point
firstControlPoints[i] = new Point(x[i], y[i]);
// Second control point
if (i < n - 1)
secondControlPoints[i] = new Point(2 * knots
[i + 1].X - x[i + 1], 2 *
knots[i + 1].Y - y[i + 1]);
else
secondControlPoints[i] = new Point((knots
[n].X + x[n - 1]) / 2,
(knots[n].Y + y[n - 1]) / 2);
}
}
private static double[] GetFirstControlPoints(double[] rhs)
{
int n = rhs.Length;
double[] x = new double[n]; // Solution vector.
double[] tmp = new double[n]; // Temp workspace.
double b = 2.0;
x[0] = rhs[0] / b;
for (int i = 1; i < n; i++) // Decomposition and forward substitution.
{
tmp[i] = 1 / b;
b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
x[i] = (rhs[i] - x[i - 1]) / b;
}
for (int i = 1; i < n; i++)
x[n - i - 1] -= tmp[n - i] * x[n - i]; // Backsubstitution.
return x;
}
}
thanks.
double[] tmp = new double[n];
tmp is an array of length n. Each value is not initialized explicitly, but it is implicitly set to the default value of the double type, which is 0. So tmp is an n length array of zeros. {0,0,0,0,0, ... 0}

Categories