1

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?

5
  • 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 to align the summation direction to the vertical or horizontal and then sum, although there would be changes in the values due to interpolation... Commented Jun 5, 2018 at 12:53
  • 1
    How 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. Commented Jun 5, 2018 at 13:17
  • Possible duplicate of How to extract an arbitrary line of values from a numpy array? Commented Jun 5, 2018 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. Commented Jun 5, 2018 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. Commented Jun 5, 2018 at 15:43

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

3 Comments

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.
I could also give an answer for 90 and 0 degree diagonals ;)
Ha, I like your style. Plus one for wit!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.