Home > Back-end >  Matlab to Python - extracting lower subdiagonal triangle, why different order?
Matlab to Python - extracting lower subdiagonal triangle, why different order?

Time:10-04

I am translating code from MATLAB to Python. I need to extract the lower subdiagonal values of a matrix. My attempt in python seems to extract the same values (sum is equal), but in different order. This is a problem as I need to apply corrcoef after.

The original Matlab code is using an array of indices to subset a matrix.

MATLAB code:

values = 1:100;
matrix = reshape(values,[10,10]);

subdiag = find(tril(ones(10),-1));

matrix_subdiag = matrix(subdiag);

subdiag_sum = sum(matrix_subdiag);
disp(matrix_subdiag(1:10))
disp(subdiag_sum)

Output:
2 3 4 5 6 7 8 9 10 13

1530

My attempt in Python

import numpy as np

matrix = np.arange(1,101).reshape(10,10)
matrix_t = matrix.T #to match MATLAB arrangement

matrix_subdiag = matrix_t[np.tril_indices((10), k = -1)]

subdiag_sum = np.sum(matrix_subdiag)
print(matrix_subdiag[0:10], subdiag_sum))

Output: [2 3 13 4 14 24 5 15 25 35] 1530

How do I get the same order output? Where is my error?

Thank you!

CodePudding user response:

For the sum use directly numpy.triu on the non-transposed matrix:

S = np.triu(matrix, k=1).sum()
# 1530

For the indices, numpy.triu_indices_from and slicing as a flattened array:

idx = matrix[np.triu_indices_from(matrix, k=1)]

output:

array([ 2,  3,  4,  5,  6,  7,  8,  9, 10, 13, 14, 15, 16, 17, 18, 19, 20,
       24, 25, 26, 27, 28, 29, 30, 35, 36, 37, 38, 39, 40, 46, 47, 48, 49,
       50, 57, 58, 59, 60, 68, 69, 70, 79, 80, 90])
  • Related