0

I'm relatively new to python/numpy. I have a 3D numpy array of TxNxN. It contains a sequence of symmetrical NxN matrices. I want convert it to a 2D array of TxM (where M = N(N+1)/2). How can I do that? I can certainly use 3 loops, but I thought there probably better ways to do that in python/numpy.

3
  • You need to understand slicing in numpy first, thats the direction to look at, and it can be done on 1 loop, by iterating only on the 3rd dimension. on each iteration you will need to instantiate and create a 2D array that you can store either on a list, a variable, a file (probably as an image, I have no context on your problem). Commented May 25, 2022 at 3:29
  • Show us the 3 loops first! And as a bonus - your attempt(s) at "better" ways. Commented May 25, 2022 at 3:32
  • Basically: 1. do a for loop across the X dimension (in this case I'll take the 3rd for example), in this case: for k in range(N) 2. do something for each iteration of k. Example: slice = my3dnumpyarray[:, :, k] Note: each : means that you are taking the whole range (domain) of that dimension, if the first dimension goes from 0 to T - 1 then the first : means exactly that Commented May 25, 2022 at 3:32

1 Answer 1

1

It seems that you want to get the upper triangle or lower triangle of each symmetric matrix. A simple method is to generate a mask array and apply it to each 2D array:

>>> e
array([[[0, 1, 2, 3],
        [1, 2, 3, 0],
        [2, 3, 0, 1],
        [3, 0, 1, 2]],

       [[1, 2, 3, 4],
        [2, 3, 4, 1],
        [3, 4, 1, 2],
        [4, 1, 2, 3]],

       [[2, 3, 4, 5],
        [3, 4, 5, 2],
        [4, 5, 2, 3],
        [5, 2, 3, 4]]])
>>> ii, jj = np.indices(e.shape[1:])
>>> jj >= ii
array([[ True,  True,  True,  True],
       [False,  True,  True,  True],
       [False, False,  True,  True],
       [False, False, False,  True]])
>>> e[:, jj >= ii]
array([[0, 1, 2, 3, 2, 3, 0, 0, 1, 2],
       [1, 2, 3, 4, 3, 4, 1, 1, 2, 3],
       [2, 3, 4, 5, 4, 5, 2, 2, 3, 4]])

Using the numpy.triu_indices function can do better, but you can't put the obtained indices tuple directly between square brackets. You need to unpack them first:

>>> i, j = np.triu_indices(e.shape[1])
>>> e[:, i, j]
array([[0, 1, 2, 3, 2, 3, 0, 0, 1, 2],
       [1, 2, 3, 4, 3, 4, 1, 1, 2, 3],
       [2, 3, 4, 5, 4, 5, 2, 2, 3, 4]])
Sign up to request clarification or add additional context in comments.

Comments

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.