Search code examples
pythonnumpymatrixwolfram-mathematica

Assign values from small matrix to specified places in larger matrix


I would like to know if there exists a similar way of doing this (Mathematica) in Python: Mathematica

I have tried it in Python and it does not work. I have also tried it with numpy.put() or with simple 2 for loops. This 2 ways work properly but I find them very time consuming with larger matrices (3000×3000 elements for example).

Described problem in Python,

import numpy as np

a = np.arange(0, 25, 1).reshape(5, 5)
b = np.arange(100, 500, 100).reshape(2, 2)
p = np.array([0, 3])

a[p][:, p] = b

which outputs non-changed matrix a: Python


Solution

  • Perhaps you are looking for this:

    a[p[...,None], p] = b
    

    Array a after the above assignment looks like this:

    [[100   1   2 200   4]
     [  5   6   7   8   9]
     [ 10  11  12  13  14]
     [300  16  17 400  19]
     [ 20  21  22  23  24]]
    

    As documented in Integer Array Indexing, the two integer index arrays will be broadcasted together, and iterated together, which effectively indexes the locations a[0,0], a[0,3], a[3,0], and a[3,3]. The assignment statement would then perform an element-wise assignment at these locations of a, using the respective element-values from RHS.