Is it possible to sum elements in an numpy array along an angle and not an axis.
I'm working with 2d arrays and it is only possible to sum along axis=0
or axis=1
.
What i want is to sum along e.g. an degree of 45 or 60.
Example:
Matrix: [[1, 2], [3, 4]]
and Angle: 45 degree.
The result should be something like [3, 1+4, 2] = [3, 5, 2]
(sum from top left to bottom right).
Anyone an idea?
Asked
Active
Viewed 1,318 times
1
-
This is complicated because each sum has a different number of elements. One approach could be rotating the matrix as if it were an image (e.g. with [`skimage.transform.rotate`](http://scikit-image.org/docs/stable/api/skimage.transform.html#skimage.transform.rotate) to align the summation direction to the vertical or horizontal and then sum, although there would be changes in the values due to interpolation... – jdehesa Jun 05 '18 at 12:53
-
1How do you define a diagonal that is at 60 degrees? Doing the sum on 45 degrees is simple, but I do not even know how to define the 60 degree diagonal. NOTE: this will depend on the shape of your matrix. – tnknepp Jun 05 '18 at 13:17
-
Possible duplicate of [How to extract an arbitrary line of values from a numpy array?](https://stackoverflow.com/questions/7878398/how-to-extract-an-arbitrary-line-of-values-from-a-numpy-array) – AGN Gazer Jun 05 '18 at 13:23
-
I do not think you need to rotate _the image_. Instead use some method of interpolating the image, and then define a set of uniformly spaced points along a _rotated extraction line_. Finally, use `np.cumsum()` to add the points (point values) along the extraction line. – AGN Gazer Jun 05 '18 at 13:59
-
Just get a list of lists of the desired values and sum them. With the normal diagonal that is easy. But you haven't defined the `60` deg diagonal. – hpaulj Jun 05 '18 at 15:43
1 Answers
1
Its easy for what you call "45 degrees": numpy trace
import numpy as np
a = np.array([[1,2],[3,4]])
np.trace(a)
5
np.trace(a, offset=1)
2
np.trace(a, offset=-1)
3
and as a list:
>>> [np.trace(a,offset=i) for i in range(-np.shape(a)[0]+1, np.shape(a)[1])]
[3, 5, 2]

Jonas
- 1,838
- 4
- 19
- 35
-
I did not know about trace, thanks. I was using np.diagonal in a similar fashion. However, the real question remains: how does the OP define non-45 degree diagonals. – tnknepp Jun 05 '18 at 13:55
-
2
-