diff --git a/matrix/SparseVector.hpp b/matrix/SparseVector.hpp index ae7cc3a608..7e1631183b 100644 --- a/matrix/SparseVector.hpp +++ b/matrix/SparseVector.hpp @@ -60,7 +60,7 @@ private: } public: - static constexpr size_t non_zeros() { + constexpr size_t non_zeros() const { return N; } @@ -94,6 +94,16 @@ public: return _data[compressed_index]; } + inline Type atCompressedIndex(size_t i) const { + assert(i < N); + return _data[i]; + } + + inline Type& atCompressedIndex(size_t i) { + assert(i < N); + return _data[i]; + } + void setZero() { for (size_t i = 0; i < N; i++) { _data[i] = Type(0); diff --git a/test/sparseVector.cpp b/test/sparseVector.cpp index 2b0dc0c3bb..4bfb718bd1 100644 --- a/test/sparseVector.cpp +++ b/test/sparseVector.cpp @@ -31,6 +31,16 @@ TEST(sparseVectorTest, initialisationFromVector) { EXPECT_FLOAT_EQ(a.at<2>(), vec(2)); } +TEST(sparseVectorTest, accessDataWithCompressedIndices) { + const Vector3f vec(1.f, 2.f, 3.f); + SparseVectorf<3, 0, 2> a(vec); + for (size_t i = 0; i < a.non_zeros(); i++) { + a.atCompressedIndex(i) = static_cast(i); + } + EXPECT_FLOAT_EQ(a.at<0>(), a.atCompressedIndex(0)); + EXPECT_FLOAT_EQ(a.at<2>(), a.atCompressedIndex(1)); +} + TEST(sparseVectorTest, setZero) { const float data[3] = {1.f, 2.f, 3.f}; SparseVectorf<24, 4, 6, 22> a(data);