From 0219f8aed44279858330b1c07402c066f5b75459 Mon Sep 17 00:00:00 2001 From: Benoit Steiner Date: Fri, 10 Oct 2014 16:17:26 -0700 Subject: Added ability to print a tensor using an iostream. --- unsupported/Eigen/CXX11/Tensor | 2 ++ unsupported/Eigen/CXX11/src/Tensor/TensorIO.h | 44 +++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 unsupported/Eigen/CXX11/src/Tensor/TensorIO.h (limited to 'unsupported/Eigen/CXX11') diff --git a/unsupported/Eigen/CXX11/Tensor b/unsupported/Eigen/CXX11/Tensor index 5a6246a03..79510fd96 100644 --- a/unsupported/Eigen/CXX11/Tensor +++ b/unsupported/Eigen/CXX11/Tensor @@ -64,6 +64,8 @@ #include "unsupported/Eigen/CXX11/src/Tensor/TensorFixedSize.h" #include "unsupported/Eigen/CXX11/src/Tensor/TensorMap.h" +#include "unsupported/Eigen/CXX11/src/Tensor/TensorIO.h" + #include "Eigen/src/Core/util/ReenableStupidWarnings.h" #endif // EIGEN_CXX11_TENSOR_MODULE diff --git a/unsupported/Eigen/CXX11/src/Tensor/TensorIO.h b/unsupported/Eigen/CXX11/src/Tensor/TensorIO.h new file mode 100644 index 000000000..959b5db73 --- /dev/null +++ b/unsupported/Eigen/CXX11/src/Tensor/TensorIO.h @@ -0,0 +1,44 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_IO_H +#define EIGEN_CXX11_TENSOR_TENSOR_IO_H + +namespace Eigen { + +template +std::ostream& operator << (std::ostream& os, const TensorBase& expr) { + // Evaluate the expression if needed + TensorForcedEvalOp eval = expr.eval(); + TensorEvaluator, DefaultDevice> tensor(eval, DefaultDevice()); + tensor.evalSubExprsIfNeeded(NULL); + + typedef typename T::Scalar Scalar; + typedef typename T::Index Index; + typedef typename TensorEvaluator, DefaultDevice>::Dimensions Dimensions; + const Index total_size = internal::array_prod(tensor.dimensions()); + + // Print the tensor as a 1d vector or a 2d matrix. + if (internal::array_size::value == 1) { + Map > array(tensor.data(), total_size); + os << array; + } else { + const Index first_dim = tensor.dimensions()[0]; + Map > matrix(tensor.data(), first_dim, total_size/first_dim); + os << matrix; + } + + // Cleanup. + tensor.cleanup(); + return os; +} + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_IO_H -- cgit v1.2.3