Reputation: 595
I have an array as follows:
A =
[[ 1. 2. 3. 0. 0. 0. 0.]
[ 4. 5. 6. 0. 0. 0. 0.]
[ 7. 8. 9. 0. 0. 0. 0.]
[ 10. 11. 12. 0. 0. 0. 0.]
[ 13. 14. 15. 0. 0. 0. 0.]
[ 16. 17. 18. 0. 0. 0. 0.]
[ 19. 20. 21. 0. 0. 0. 0.]
[ 22. 23. 24. 0. 0. 0. 0.]
[ 25. 26. 27. 0. 0. 0. 0.]
[ 28. 29. 30. 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.]]
I also have a vector, v=[10, 3]
, that tells me where I need to slice to obtain the submatrix at the top left-hand corner:
A[0:v[0], 0:v[1]] =
[[ 1. 2. 3.]
[ 4. 5. 6.]
[ 7. 8. 9.]
[ 10. 11. 12.]
[ 13. 14. 15.]
[ 16. 17. 18.]
[ 19. 20. 21.]
[ 22. 23. 24.]
[ 25. 26. 27.]
[ 28. 29. 30.]]
Suppose I now have an n-dimensional array, A_n
, with a submatrix at the top left-hand corner of it, as is the case above. Again, there is a vector v_n
that tells me the range of my submatrix.
How do I slice the n-dimensional array with the vector without writing each index range by hand i.e. A_n[0:v_n[0], 0:v_n[1], 0:v_n[2] ...]
?
Upvotes: 1
Views: 81
Reputation: 6495
I think it is enough to convert A_n
into a numpy array, and then slice it using a list comprehension:
A_n = np.array(A_n)
A_sliced = A_n[[slice(i) for i in v_n]]
Upvotes: 1
Reputation: 477641
You can construct a tuple of slice
objects (which the colon representation basically represent) through a mappinng:
A_n[tuple(map(slice, V_n))]
So if V_n = [10, 3]
, we will pass it:
>>> tuple(map(slice, [10, 3]))
(slice(None, 10, None), slice(None, 3, None))
This is basically a desugared version of what [:10, :3]
means.
Upvotes: 3
Reputation: 2086
Check the below code:
A = [[1., 2., 3., 0., 0., 0., 0.], [4., 5., 6., 0., 0., 0., 0.], [7., 8., 9., 0., 0., 0., 0.],
[10., 11., 12., 0., 0., 0., 0.], [13., 14., 15., 0., 0., 0., 0.], [16., 17., 18., 0., 0., 0., 0.],
[19., 20., 21., 0., 0., 0., 0.], [22., 23., 24., 0., 0., 0., 0.], [25., 26., 27., 0., 0., 0., 0.],
[28., 29., 30., 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.]]
n = [10,3]
arrayA = []
for i in range(0,n[0]):
tempArray = []
for j in range(0,n[1]):
tempArray.append(j)
arrayA.append(tempArray)
print(arrayA)
Upvotes: 0