[Python] Python fill in elements of large matrix with same value

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    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)

    Continue reading...

Compartilhe esta Página