Filling the diagonals of square matrices inside a 3D ndarray with values given by a 2D ndarray

前端 未结 1 591
梦毁少年i
梦毁少年i 2020-12-21 20:58

Given a 3D ndarray z with shape (k,n,n), is it possbile without using iteration to fill the diagonals of the k nxn matrices with values given by a

相关标签:
1条回答
  • 2020-12-21 21:47

    Here's for generic n-dim arrays -

    diag_view = np.einsum('...ii->...i',z)
    diag_view[:] = v
    

    Another with reshaping -

    n = v.shape[-1] 
    z.reshape(-1,n**2)[:,::n+1] = v.reshape(-1,n)
    # or z.reshape(z.shape[:-2]+(-1,))[...,::n+1] = v
    

    Another with masking -

    m = np.eye(n, dtype=bool) # n = v.shape[-1] from earlier
    z[...,m] = v
    

    Initializing output z

    If we need to initialize the output array z and one that will cover for generic n-dim cases, it would be :

    z = np.zeros(v.shape + (v.shape[-1],), dtype=v.dtype)
    

    Then, we proceed with the earlier listed approaches.

    0 讨论(0)
提交回复
热议问题