我正在將代碼從 MATLAB 翻譯成 Python。我需要提取矩陣的下對角線值。我在 python 中的嘗試似乎提取了相同的值(總和相等),但順序不同。這是一個問題,因為我需要在之后應用 corrcoef。
原始的 Matlab 代碼使用索引陣列來對矩陣進行子集化。
MATLAB代碼:
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)
輸出:
2 3 4 5 6 7 8 9 10 13
1530
我在 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))
輸出:[2 3 13 4 14 24 5 15 25 35] 1530
如何獲得相同的訂單輸出?我的錯誤在哪里?
謝謝!
uj5u.com熱心網友回復:
對于直接numpy.triu在非轉置矩陣上使用的總和:
S = np.triu(matrix, k=1).sum()
# 1530
對于索引,numpy.triu_indices_from并切片為扁平陣列:
idx = matrix[np.triu_indices_from(matrix, k=1)]
輸出:
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])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511572.html
