1
  • I'm extracting a sub matrix from a quadratic matrix using a list of indexes.
  • The index list applies to both rows and columns.
  • The sub matrix is updated.
  • Finally the sub matrix is merged back in the original matrix.
  • The extract function is short and fast.
  • The merge function is longer and slower, as explicit loops are killing performance
  • Is there a better way of writing merge?

    import numpy as np
    
    def extract(a,indexes): 
        return a[indexes].T[indexes].T
    
    def merge(a,indexes,b): 
        for i,ix in enumerate(indexes):
            for j,jx in enumerate(indexes):
                a[ix,jx] = b[i,j]
        return a
    
    N = 10
    a = np.array(np.arange(N*N)).reshape(N,N)
    
    indexes = [0,2,4,6,8]
    b = extract(a,indexes)
    
    print(a)
    print(indexes)
    print(b)
    
    # make some changes in b
    b=-b
    
    res = merge(a,indexes,b)
    

https://docs.scipy.org/doc/numpy-1.10.0/user/basics.indexing.html#index-arrays

a:
[[ 0  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 31 32 33 34 35 36 37 38 39]
 [40 41 42 43 44 45 46 47 48 49]
 [50 51 52 53 54 55 56 57 58 59]
 [60 61 62 63 64 65 66 67 68 69]
 [70 71 72 73 74 75 76 77 78 79]
 [80 81 82 83 84 85 86 87 88 89]
 [90 91 92 93 94 95 96 97 98 99]]

indexes: [0, 2, 4, 6, 8]

b: 
[[ 0  2  4  6  8]
 [20 22 24 26 28]
 [40 42 44 46 48]
 [60 62 64 66 68]
 [80 82 84 86 88]]

res:  [[  0,   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,  31,  32,  33,  34,  35,  36,  37,  38,  39],
       [-40,  41, -42,  43, -44,  45, -46,  47, -48,  49],
       [ 50,  51,  52,  53,  54,  55,  56,  57,  58,  59],
       [-60,  61, -62,  63, -64,  65, -66,  67, -68,  69],
       [ 70,  71,  72,  73,  74,  75,  76,  77,  78,  79],
       [-80,  81, -82,  83, -84,  85, -86,  87, -88,  89],
       [ 90,  91,  92,  93,  94,  95,  96,  97,  98,  99]])

1 Answer 1

1

You can use np.ix_ to form such a grid spread across rows and columns. So, simply index into input array with it and assign the negated b values, like so -

idx_grid = np.ix_(indexes, indexes)
a[idx_grid] = -b
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.