From a0851f0eb41b3c76f0eb83dc88d67ce81dc613d0 Mon Sep 17 00:00:00 2001 From: Chris Beall Date: Tue, 19 Jun 2012 18:03:01 +0000 Subject: [PATCH] reshape matrix to tensor --- gtsam/geometry/tensorInterface.h | 12 ++++++++++++ gtsam/geometry/tests/testTensors.cpp | 4 ++++ 2 files changed, 16 insertions(+) diff --git a/gtsam/geometry/tensorInterface.h b/gtsam/geometry/tensorInterface.h index 61212e2c9..7a2c144d7 100644 --- a/gtsam/geometry/tensorInterface.h +++ b/gtsam/geometry/tensorInterface.h @@ -60,6 +60,18 @@ namespace gtsam { return tensors::Tensor2(data); } + /** Reshape Matrix into rank 2 tensor */ + template + tensors::Tensor2 reshape2matrix(const Matrix& m) { + if (m.rows() * m.cols() != N1 * N2) throw std::invalid_argument( + "reshape2: incompatible dimensions"); + double data[N2][N1]; + for (int j = 0; j < N2; j++) + for (int i = 0; i < N1; i++) + data[j][i] = m(j,i); + return tensors::Tensor2(data); + } + /** Reshape rank 3 tensor into Matrix */ template Matrix reshape(const tensors::Tensor3Expression& T, int m, int n) { diff --git a/gtsam/geometry/tests/testTensors.cpp b/gtsam/geometry/tests/testTensors.cpp index 85437b850..0e1c381cf 100644 --- a/gtsam/geometry/tests/testTensors.cpp +++ b/gtsam/geometry/tests/testTensors.cpp @@ -188,6 +188,10 @@ TEST( Tensor2, reshape2 ) { Tensor2<3,4> actual = reshape2<3,4>(camera::vector); CHECK(assert_equality(camera::M(a,A),actual(a,A))); + + // reshape Matrix to rank 2 tensor + Tensor2<3,4> actual_m = reshape2matrix<3,4>(camera::matrix); + CHECK(assert_equality(camera::M(a,A), actual_m(a,A))); } /* ************************************************************************* */