Browse Source

Added static initializer for identity matrix.

la-knuth
Jurgen Van Gael 17 years ago
parent
commit
7f747ad1f3
  1. 19
      src/Numerics/LinearAlgebra/Double/DenseMatrix.cs
  2. 29
      src/UnitTests/LinearAlgebraTests/Double/DenseMatrixTests.cs

19
src/Numerics/LinearAlgebra/Double/DenseMatrix.cs

@ -397,5 +397,24 @@ namespace MathNet.Numerics.LinearAlgebra.Double
} }
#endregion #endregion
#region Static constructors for special matrices.
/// <summary>
/// Initializes a square <see cref="DenseMatrix"/> with all zero's except for ones on the diagonal.
/// </summary>
/// <param name="order">the size of the square matrix.</param>
/// <exception cref="ArgumentException">
/// If <paramref name="order"/> is less than one.
/// </exception>
public static DenseMatrix Identity(int order)
{
var m = new DenseMatrix(order);
for (int i = 0; i < order; i++)
{
m[i, i] = 1.0;
}
return m;
}
#endregion
} }
} }

29
src/UnitTests/LinearAlgebraTests/Double/DenseMatrixTests.cs

@ -120,5 +120,34 @@ namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double
} }
} }
} }
[Test]
public void CanCreateIdentity()
{
var matrix = DenseMatrix.Identity(5);
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
if (i == j)
{
Assert.AreEqual(1.0, matrix[i, j]);
}
else
{
Assert.AreEqual(0.0, matrix[i, j]);
}
}
}
}
[Test]
[Row(0)]
[Row(-1)]
[ExpectedArgumentException]
public void IdentityFailsWithZeroOrNegativeOrder(int order)
{
var matrix = DenseMatrix.Identity(order);
}
} }
} }

Loading…
Cancel
Save