This question is quite similar for matrices Roll rows of a matrix independently
But i'm failing to adapt it for 3D tensors
I'm given a tensor
0 0 0
1 1 1
0 0 0
0 0 0
1 1 1
0 0 0
and a vector that specifies by how much I want to shift my matrices column wise
1 2
I want a new tensor where each matrix has been shiften column wise like so
0 0 0
0 0 0
1 1 1
1 1 1
0 0 0
0 0 0
So far I have been able to get a potential mapping indices
import numpy as np
# Input
A = np.array([[0, 0, 0],
[1, 1, 1],
[0, 0, 0],
[0, 0, 0]])
B = np.array([[0, 0, 0],
[1, 1, 1],
[0, 0, 0],
[0, 0, 0]])
AB = np.array([A, B])
# Shifting amount
r = np.array([-1, 1])
d1, d2, d3 = np.ogrid[:AB.shape[0], :AB.shape[1], :AB.shape[2]]
r[r < 0] += AB.shape[1]
r = np.array([r, ]*AB.shape[1]).transpose()
r = r[:, np.newaxis]
# New column indices?
d2 = d2 - r
d2[d2 < 0] += AB.shape[1]
result = AB[d2]
print(result)
But I get this error :
~/Work/ethz/iml/task2 $ python test.py
Traceback (most recent call last):
File "test.py", line 27, in <module>
result = AB[d2]
IndexError: index 2 is out of bounds for axis 0 with size 2
This is what d2
looks like :
[[[1 1 1 1]
[2 2 2 2]
[3 3 3 3]
[0 0 0 0]]
[[3 3 3 3]
[0 0 0 0]
[1 1 1 1]
[2 2 2 2]]]