diff --git a/src/Numerics/LinearAlgebra/Storage/SparseCompressedRowMatrixStorage.cs b/src/Numerics/LinearAlgebra/Storage/SparseCompressedRowMatrixStorage.cs index ca96cc4e..148c4841 100644 --- a/src/Numerics/LinearAlgebra/Storage/SparseCompressedRowMatrixStorage.cs +++ b/src/Numerics/LinearAlgebra/Storage/SparseCompressedRowMatrixStorage.cs @@ -152,17 +152,17 @@ namespace MathNet.Numerics.LinearAlgebra.Storage return; } - for (int i = rowIndex, row = 0; i < rowIndex + rowCount; i++, row++) + for (int i = rowIndex + rowCount - 1, row = rowCount - 1; i >= rowIndex; i--, row--) { var startIndex = RowPointers[i]; var endIndex = i < RowPointers.Length - 1 ? RowPointers[i + 1] : ValueCount; - for (int j = startIndex; j < endIndex; j++) + for (int j = endIndex - 1; j >= startIndex; j--) { // check if the column index is in the range if ((ColumnIndices[j] >= columnIndex) && (ColumnIndices[j] < columnIndex + columnCount)) { - var column = ColumnIndices[j] - columnIndex; + var column = ColumnIndices[j]; // NOTE: potential for more efficient implementation At(row, column, _zero); diff --git a/src/UnitTests/LinearAlgebraTests/MatrixStructureTheory.cs b/src/UnitTests/LinearAlgebraTests/MatrixStructureTheory.cs index bbf8a1c8..29bbf4aa 100644 --- a/src/UnitTests/LinearAlgebraTests/MatrixStructureTheory.cs +++ b/src/UnitTests/LinearAlgebraTests/MatrixStructureTheory.cs @@ -120,6 +120,20 @@ namespace MathNet.Numerics.UnitTests.LinearAlgebraTests Assert.That(cleared, Is.EqualTo(matrix.CreateMatrix(matrix.RowCount, matrix.ColumnCount))); } + [Theory, Timeout(200)] + public void CanClearSubMatrix(Matrix matrix) + { + var cleared = matrix.Clone(); + Assume.That(cleared.RowCount, Is.GreaterThanOrEqualTo(2)); + Assume.That(cleared.ColumnCount, Is.GreaterThanOrEqualTo(2)); + + cleared.Storage.Clear(0,2,1,1); + Assert.That(cleared.At(0, 0), Is.EqualTo(matrix.At(0, 0))); + Assert.That(cleared.At(1, 0), Is.EqualTo(matrix.At(1, 0))); + Assert.That(cleared.At(0, 1), Is.EqualTo(Zero)); + Assert.That(cleared.At(1, 1), Is.EqualTo(Zero)); + } + [Theory, Timeout(200)] public void CanToArray(Matrix matrix) {