diff --git a/LinearAlgebra/Matrix.cs b/LinearAlgebra/Matrix.cs index c0abac8..5a82109 100644 --- a/LinearAlgebra/Matrix.cs +++ b/LinearAlgebra/Matrix.cs @@ -8,6 +8,14 @@ public class Matrix { this.cols = cols; } + public static float[,] Diagonal(float[] v) { + float[,] r = new float[v.Length, v.Length]; + for (int i = 0; i < v.Length; i++) { + r[i, i] = v[i]; + } + return r; + } + public static float[,] Transpose(float[,] m) { int rows = m.GetLength(0); int cols = m.GetLength(1); @@ -31,14 +39,15 @@ public class Matrix { if (n != matrix.GetLength(1)) throw new System.ArgumentException("Matrix must be square."); - if (n == 1) return matrix[0, 0]; // Base case for 1x1 matrix + if (n == 1) + return matrix[0, 0]; // Base case for 1x1 matrix + if (n == 2) // Base case for 2x2 matrix return matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0]; float det = 0; - for (int col = 0; col < n; col++) { + for (int col = 0; col < n; col++) det += (col % 2 == 0 ? 1 : -1) * matrix[0, col] * Determinant(Minor(matrix, 0, col)); - } return det; }