Fs02
Fs02

Reputation: 101

How to transpose Tensor in Eigen

I'm trying to get matrix product of two tensors, where one of the tensor should be transposed before it multiplied (At*B).

So far what I've found in eigen documentation is matrix product without any transposed and with both matrix transposed.

I'm looking for a way to either directly contracting two tensor with one of the tensor is transposed, or either by transposing one tensor before contracting it.

Upvotes: 4

Views: 2967

Answers (2)

Benoit Steiner
Benoit Steiner

Reputation: 1469

You can also use the contraction directly:

Eigen::Tensor<int, 2> A(3, 5);
Eigen::Tensor<int, 2> B(3, 5);
Eigen::array<int, 1> contraction_indices;
// This will contract the first dimension of A with the first dim of B,
// effectively computing At*B
contraction_indices[0] = {0, 0};
Eigen::Tensor<int, 2> Result = A.contract(B, contraction_indices);

Upvotes: 3

Fs02
Fs02

Reputation: 101

I figured it out, transpose effect can be done using shuffle method.

Eigen::Tensor<int, 2> m(3, 5);
m.setValues(
{
    {1, 2, 3, 4, 5},
    {6, 7, 8, 9, 10},
    {11, 12, 13, 14, 15}
});

Eigen::array<int, 2> shuffling({1, 0});

Eigen::Tensor<int, 2> transposed = m.shuffle(shuffling);
Eigen::Tensor<int, 2> original = transposed.shuffle(shuffling);

Upvotes: 6

Related Questions