Python fill in elements of large matrix with same value

Python fill in elements of large matrix with same value

I have a large matrix where I want to assign the same value(s) to many matrix elements. Is there a more efficient way to do this rather than iterating over each column and row using for loops? Here is a MWE:

import numpy as np

a = 0.5 
b = 0.6

M = np.zeros((16,16))  # empty matrix
np.fill_diagonal(M, 0.9)  # diagonal elements

for jj in range(0,16):  # rows
    for kk in range(0,16):  # columns
        if jj == 0:
            if (kk == 1) | (kk == 3):
                M[jj,kk] = a
        if jj == 3:
            if (kk == 0) | (kk == 2):
                M[jj,kk] = b
        if jj == 5:
            if (kk == 4) | (kk == 6):
                M[jj,kk] = a
        # etc

print(M)

Answer

A possible solution:

idxr_a = [0, 0, 5, 5] # row index
idxc_a = [1, 3, 4, 6] # col index
M[idxr_a, idxc_a] = a

idxr_b = [3, 3] # row index
idxc_b = [0, 2] # col index
M[idxr_b, idxc_b] = b

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions