xtensor
xtensor copied to clipboard
About intermediates
I noticed that in the documentation, there is a session "Intermediate result" in "common pitfalls" .
Using intermediate variables in a function will cause an error because the tmp
is destoyed when lazy evaluation starts. But evaluation depends on it.
template <class C>
auto func(const C& c)
{
auto tmp = func_tmp(c);
return (1 - tmp) / (1 + tmp);
}
Are users forced not to use any temporary variable then? Without using temporary valuables, it would be hard to write complicated function.
So I wonder how is this different from the lazy evaluation mechanism in Eigen. Because we can use temporary variable in function that takes as input Eigen::TensorBase and return Eigen::TensorBase.
xtensor
#include <iostream>
#include <vector>
#include <xtensor/xtensor.hpp>
#include <xtensor/xarray.hpp>
#include <xtensor/xio.hpp>
#include <xtensor/xview.hpp>
template <typename T>
auto func(const T& input, const std::vector<int>& axes){
auto temp = xt::sum(input, axes);
auto result = temp * temp;
return result;
}
int main(){
xt::xarray<double> a{{1, 2}, {3, 4}};
xt::xarray<double> b = func(a, {0});
std::cout << b << std::endl;
return 0;
}
It would output
a:
{{ 1., 2.},
{ 3., 4.}}
b:
{}
Eigen
#include <iostream>
#include <unsupported/Eigen/CXX11/Tensor>
template <typename T, typename A>
auto func(const T& input, const A& axes){
auto temp = input.sum(axes);
auto result = temp * temp;
return result;
}
int main(){
Eigen::Tensor<float, 2> a(2, 2);
a.setValues({{1, 2}, {3, 4}});
std::cout << "a:\n" << a << std::endl;
Eigen::array<int, 1> axes {0};
auto x = func(a, axes);
std::cout << "x:\n" << x << std::endl;
return 0;
}
it would output
a:
1 2
3 4
x:
16
36
Thank you!