# Averaging upper and lower triangle of a matrix

Hello, I have a tensor of shape N * X * Y where N is the number of subjects. I want to average the upper and lower triangle for each matrix i in N. For example if subject 1 has the matrix:

tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Then the output should be:

tensor([[1, 3, 5],
[3, 5, 7],
[5, 7, 9]])
So, adding upper and lower triangle and dividing each value of two, the main diagonal remains same as you add each number with itself and divide by 2. I know I can loop through each subject, get the upper and lower triangle using `torch.` `triu` and `torch.` `tril`, add them together and take average and put them back in the array.
But I am looking for a faster method , specially without the loop.
Thank you

@ptrblck Any help on this?

Hi Usman!

Probably the most direct approach is to average the matrix with its
transpose. Here is an illustration for the 3-dimensional-tensor use
case you mention:

``````>>> torch.__version__
'1.7.1'
>>> t = torch.tensor ([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 20, 30], [40, 50, 60], [70, 80, 90]]])
>>> (t + t.transpose (1, 2)) / 2
tensor([[[ 1.,  3.,  5.],
[ 3.,  5.,  7.],
[ 5.,  7.,  9.]],

[[10., 30., 50.],
[30., 50., 70.],
[50., 70., 90.]]])
``````

Best.

K. Frank