Issue
I'm having trouble reshaping the matrix in python.
Suppose I have four (5,5,3) matrix
a = [[[0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0]],
[[0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0]],
[[0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0]],
[[0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0]],
[[0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0]]]
b = [[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]]
c = [[[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
[[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
[[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
[[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
[[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],]
d = [[[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],
[[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],
[[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],
[[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],
[[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],]
I want to put this matrix together in the form of (5,5,4,3). like
result = [[[[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]],
[[[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]],
[[[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]],
[[[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]],
[[[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]], [[0,0,0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]]]
I would appreciate it if you could let me know if you have any good ideas for the solution.
Solution
You can stack
them as numpy arrays and then convert back to list:
stacked = np.stack([a,b,c,d], axis=2).tolist()
Verify with your result
: np.array_equal(stacked, result)
return True
.
Answered By - Stef
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.