Omroth
(Ian)
March 9, 2021, 9:41am
#1
Hi guys.

I’m creating a rotation matrix as a pytorch c++ tensor:

Where theta needs to be another tensor, which has requires_grad=true.

What would be the best practice way of initialising this tensor given the theta tensor? Do I just set each element manually, or is there some more clever way?

Cheers.

Omroth
(Ian)
March 10, 2021, 8:13am
#2
I’m clearly not using the right method. As a test I have:

```
torch::Tensor theta = torch::tensor({0.18}, torch::dtype(torch::kFloat32).requires_grad(true));
torch::Tensor cos_theta = torch::cos(theta);
torch::Tensor t = torch::eye(4, torch::dtype(torch::kFloat32).requires_grad(false));
t.index({0,0}) = cos_theta;
```

This produces an error:

```
output with shape [] doesn't match the broadcast shape [1]
```

And doesn’t seem like the right way of doing it either. Eventually I want to set each element of the tensor matrix individually with other tensors, such as:

```
t.index({0,0}) = cos_theta + (ux * (ux * one_minus_cos_theta));
t.index({0,1}) = (ux * uy * one_minus_cos_theta) - (uz * sin_theta);
t.index({0,2}) = (ux * uz * one_minus_cos_theta) + (uy * sin_theta);
//
t.index({1,0}) = (uy * ux * one_minus_cos_theta) + (uz * sin_theta);
t.index({1,1}) = cos_theta + (uy * uy * one_minus_cos_theta);
t.index({1,2}) = (uy * uz * one_minus_cos_theta) - (ux * sin_theta);
//
t.index({2,0}) = (uz * ux * one_minus_cos_theta) - (uy * sin_theta);
t.index({2,1}) = (uz * uy * one_minus_cos_theta) + (ux * sin_theta);
t.index({2,2}) = cos_theta + (uz * uz * one_minus_cos_theta);
```

I think I’m probably missing something conceptually with how to construct a tensor matrix out of individual tensor calculations - can someone assist?

Omroth
(Ian)
March 10, 2021, 8:19am
#3
Ah, it looks like the problem is with using .index. if I use t[0] it at least doesn’t crash.

I’m still interested in feedback on whether this is how you would approach the problem though.