Anonymous avatar Anonymous committed 654e176

More matrix operations

Comments (0)

Files changed (1)

neglect/cpplib/include/neglect/matrix.hpp

         matrix<T, M, P> rv;
         for (size_t i = 0; i < M; i++)
             for (size_t j = 0; j < P; j++) {
+                T sum = T();
                 for (size_t k = 0; k < N; k++)
-                    rv(i, j) += lhs(i, k) * rhs(k, j);
+                    sum += lhs(i, k) * rhs(k, j);
+                rv(i, j) = sum;
             }
         return rv;
     }
         return lhs;
     }
 
+    /* multiply a matrix with a vector */
+    template <typename T, size_t M, size_t N>
+    vector<T, M> operator*(const matrix<T, M, N> &lhs,
+                           const vector<T, N> &rhs)
+    {
+        vector<T, M> rv;
+        for (size_t i = 0; i < M; i++)
+            for (size_t k = 0; k < N; k++)
+                rv[i] = lhs(i, k) * rhs[k];
+        return rv;
+    }
+
+    /* matrix addition */
+    template <typename T, size_t M, size_t N>
+    matrix<T, M, N> &operator+=(matrix<T, M, N> &lhs,
+                                const matrix<T, M, N> &rhs)
+    {
+        TA *ptr_a = lhs.ptr();
+        TB *ptr_b = rhs.ptr();
+        for (size_t i = 0; i < (M * N); i++)
+            ptr_a[i] += ptr_b[i];
+        return lhs;
+    }
+
+    template <typename T, size_t M, size_t N>
+    matrix<T, M, N> operator+(const matrix<T, M, N> &lhs,
+                              const matrix<T, M, N> &rhs)
+    {
+        matrix<T, M, N> rv = lhs;
+        rv += rhs;
+        return rv;
+    }
+
+    /* matrix subtraction */
+    template <typename T, size_t M, size_t N>
+    matrix<T, M, N> &operator-=(matrix<T, M, N> &lhs,
+                                const matrix<T, M, N> &rhs)
+    {
+        TA *ptr_a = lhs.ptr();
+        TB *ptr_b = rhs.ptr();
+        for (size_t i = 0; i < (M * N); i++)
+            ptr_a[i] -= ptr_b[i];
+        return lhs;
+    }
+
+    template <typename T, size_t M, size_t N>
+    matrix<T, M, N> operator-(const matrix<T, M, N> &lhs,
+                              const matrix<T, M, N> &rhs)
+    {
+        matrix<T, M, N> rv = lhs;
+        rv -= rhs;
+        return rv;
+    }
+
     /* creates a scale matrix */
     template <typename T>
     matrix<T, 4, 4> scale_matrix(T sx, T zy, T sz)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.