4

I came across this python code (which works) and to me it seems amazing. However, I am unable to figure out what this code is doing. To replicate it, I sort of wrote a test code:

import numpy as np

# Create a random array which represent the 6 unique coeff. 
# of a symmetric 3x3 matrix
x = np.random.rand(10, 10, 6)

So, I have 100 symmetric 3x3 matrices and I am only storing the unique components. Now, I want to generate the full 3x3 matrix and this is where the magic happens.

indices = np.array([[0, 1, 3],
                    [1, 2, 4],
                    [3, 4, 5]])

I see what this is doing. This is how the 0-5 index components should be arranged in the 3x3 matrix to have a symmetric matrix.

mat = x[..., indices]

This line has me lost. So, it is working on the last dimension of the x array but it is not at all clear to me how the rearrangement and reshaping is done but this indeed returns an array of shape (10, 10, 3, 3). I am amazed and confused!

Luca
  • 10,458
  • 24
  • 107
  • 234
  • 1
    My answer to this question: http://stackoverflow.com/questions/10921893/numpy-sorting-a-multidimensional-array-by-a-multidimensional-array/10922358#10922358 may help. – user545424 Jan 08 '15 at 23:38
  • 1
    I started to write an answer but found myself largely repeating [this reference](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer-array-indexing). If the reference is not clear, maybe update your question with the part you don't understand and we can help you more. – Bi Rico Jan 09 '15 at 01:12

1 Answers1

1

From the advanced indexing documentation - bi rico's link.

Example

Suppose x.shape is (10,20,30) and ind is a (2,3,4)-shaped indexing intp array, thenresult = x[...,ind,:] has shape (10,2,3,4,30) because the (20,)-shaped subspace has been replaced with a (2,3,4)-shaped broadcasted indexing subspace. If we let i, j, kloop over the (2,3,4)-shaped subspace then result[...,i,j,k,:] =x[...,ind[i,j,k],:]. This example produces the same result as x.take(ind, axis=-2).

Community
  • 1
  • 1
hpaulj
  • 221,503
  • 14
  • 230
  • 353