diag#

diag comes in two forms: a generator and an operator. The generator version is used to generate a diagonal tensor with a given value or a 1D input operator, while the operator pulls diagonal elements from a tensor.

Operator#

auto __MATX_INLINE__ matx::diag(const T1 &t, index_t k = 0)#

Get the elements on the diagonal (2D inputs and above), or generate a diagonal matrix (1D input)

Parameters:
  • t – Input operator

  • k – Diagonal to pull (0 is the main diagonal). Only used for 2D tensors and above

Examples#

// The generator form of `diag()` with a >= 2D input takes an operator input and returns only
// the diagonal elements as output
auto tc = make_tensor<TestType>({10, 10});
auto td = make_tensor<TestType>({10});
auto tdk = make_tensor<TestType>({4});

// Initialize the diagonal elements of `tc`
for (int i = 0; i < 10; i++) {
  for (int j = 0; j < 10; j++) {
    TestType val(static_cast<detail::value_promote_t<TestType>>(i * 10 + j));
    tc(i, j) = val;
  }
}

// Assign the diagonal elements of `tc` to `td`.
(td = diag(tc)).run(exec);
// Assign the diagonal elements of `tc` to `td` with the 6th diagonal.
auto op = diag(tc, 6);
(tdk = op).run(exec);
// Assign the diagonal elements of `tc` to `td` with the 6th diagonal.
auto op = diag(tc, -6);
(tdk = op).run(exec);

Generator#

template<typename T = int, int RANK>
inline auto matx::diag(const index_t (&s)[RANK], T val)#

Creates a diagonal tensor with a given value on the diagonals

diag returns a given value on all elements on the diagonals of a tensor, and 0 otherwise. In other words, if the index of every dimension is the same, the value is returned, otherwise a zero is returned.

Template Parameters:
  • T – Data type

  • RANK – Rank of input

Parameters:
  • s – Array of operator dimensions

  • val – Value to return

template<typename T = int, std::enable_if_t<std::is_arithmetic_v<T>, bool> = true>
inline auto matx::diag(T val)#

Creates a diagonal tensor with a given value on the diagonals

diag returns a given value on all elements on the diagonals of a tensor, and 0 otherwise. In other words, if the index of every dimension is the same, the value is returned, otherwise a zero is returned. This version of diag() is shapeless and can be indexed using any input dimension and it will return a valid value. It is preferred to use it over the shaped versions if the shape can be deduced by other contexts.

Template Parameters:

T – Data type

Parameters:

val – Value to return

Examples#

// Create a 2D, 3D, and 4D tensor and make only their diagonal elements set to `c`
auto t2 = make_tensor<TestType>({count, count});
auto t3 = make_tensor<TestType>({count, count, count});
auto t4 = make_tensor<TestType>({count, count, count, count});

auto diag2 = diag<TestType>({count, count}, c);
auto diag3 = diag<TestType>({count, count, count}, c);
auto diag4 = diag<TestType>({count, count, count, count}, c);

(t2 = diag2).run(exec);
(t3 = diag3).run(exec);
(t4 = diag4).run(exec);