Initialize a 2-D array and compute the sum of one of its rows and a 1-D array


In [ ]:
#include <iostream>
#include "xtensor/xarray.hpp"
#include "xtensor/xio.hpp"

In [ ]:
xt::xarray<double> arr1
  {{1.0, 2.0, 3.0},
   {2.0, 5.0, 7.0},
   {2.0, 5.0, 7.0}};

xt::xarray<double> arr2
  {5.0, 6.0, 7.0};

std::cout << xt::view(arr1, 1) + arr2;;

Initialize a 1-D array and reshape it inplace


In [ ]:
#include <iostream>
#include "xtensor/xarray.hpp"
#include "xtensor/xio.hpp"

In [ ]:
xt::xarray<int> arr
  {1, 2, 3, 4, 5, 6, 7, 8, 9};

arr.reshape({3, 3});

std::cout << arr;

Broadcasting the xt::pow universal functions


In [ ]:
#include <iostream>
#include "xtensor/xarray.hpp"
#include "xtensor/xmath.hpp"
#include "xtensor/xio.hpp"

In [ ]:
xt::xarray<double> arr3
  {1.0, 2.0, 3.0};

xt::xarray<unsigned int> arr4
  {4, 5, 6, 7};

arr4.reshape({4, 1});

std::cout << xt::pow(arr3, arr4);;

Random arrays with the random module


In [ ]:
#include <iostream>
#include "xtensor/xrandom.hpp"

In [ ]:
xt::xarray<double> arr5 = xt::random::randn<double>({4, 3});
std::cout << arr5;

In [ ]:
std::cout << xt::random::randn<double>({4, 3});

Using linspace, arange, ones, zeros


In [ ]:
#include "xtensor/xbuilder.hpp"

In [ ]:
xt::xarray<double> ar = xt::linspace<double>(0.0, 10.0, 12);
ar.reshape({4, 3});
std::cout << ar;

In [ ]:
xt::xarray<double> fones = xt::ones<float>({2, 2});
std::cout << fones;

Using xt::broadcast


In [ ]:
#include <vector>
#include "xtensor/xbroadcast.hpp"

In [ ]:
std::cout << xt::broadcast(xt::linspace<double>(0.0, 10.0, 4),
                           std::vector<std::size_t>({3, 4}));

Using standard algorithms with xexpressions


In [ ]:
#include <algorithm>

In [ ]:
xt::xarray<double> frand = xt::random::randn<double>({2, 2});

std::cout << frand << std::endl << std::endl;

// begin() and end() provide and iterator pair iterating over the xexpression in a row-major fashion
std::cout << std::accumulate(frand.begin(), frand.end(), 0.0);

Iterating over a prescribed broadcasted shape


In [ ]:
// xbegin(shape) and xend(shape) provide and iterator pair iterating
// over the xexpression broadcasted to the prescrived shape in a row-major fashion
std::vector<std::size_t> shape = {3, 2, 2};
std::cout << std::accumulate(frand.xbegin(shape), frand.xend(shape), 0.0);


In [ ]:
#include "xtensor-blas/xlinalg.hpp"

In [ ]:
xt::xtensor<double, 2> a = {{1.5, 0.5}, {0.7, 1.0}};

In [ ]:
std::cout << "Matrix rank: " << std::endl << xt::linalg::matrix_rank(a);

In [ ]:
std::cout << "Matrix inverse: " << std::endl << xt::linalg::inv(a);

In [ ]:
std::cout << "Eigen values: " << std::endl << xt::linalg::eigvals(a);

In [ ]: