pythonnumpytriangular

How to copy lower triangle to upper triangle for a 4 dimension array in Numpy Python?


The objective is to copy the lower triangle to upper triangle. Based on the suggestion produced in the OP, the following code was drafted.

import numpy as np

lw_up_pair = np.tril_indices(4, -1)
arr=np.zeros((4,4,1,1))

arr[1,:1,:,0]=1
arr[2,:2,0,0]=2
arr[3,:3,0,0]=3
arr = arr + arr.T - np.diag(np.diag(arr))

However, it given an error

ValueError: Input must be 1- or 2-d.

May I know how handle this issue?

The expected output is as below

[[[0.]],, [[1.]],, [[2.]],, [[3.]]]
[[[1.]],, [[0.]],, [[2.]],, [[3.]]]
[[[2.]],, [[2.]],, [[0.]],, [[3.]]]
[[[3.]],, [[3.]],, [[3.]],, [[0.]]]

Solution

  • Before performing your triangle-copy, apply a "squeeze" to squeeze out the last two axes (which have length of 1 each).

    This leaves you with a 2-D array.

    Then, after performing your triangle-copy, re-introduce the axes that you had squeezed out:

    arr = np.squeeze(arr)
    arr = arr + arr.T - np.diag(np.diag(arr))
    arr = arr[...,None, None]