この質問では、与えられた行列の三角部分lower
にアクセスする方法が説明されています。upper
m = np.matrix([[11, 12, 13],
[21, 22, 23],
[31, 32, 33]])
ここで、行列を 1D 配列に変換する必要があります。これは次のようにして実行できます。
indices = np.triu_indices_from(m)
a = np.asarray( m[indices] )[-1]
#array([11, 12, 13, 22, 23, 33])
で多くの計算を行いa
、その値を変更した後、対称 2D 配列を埋めるために使用されます。
new = np.zeros(m.shape)
for i,j in enumerate(zip(*indices)):
new[j]=a[i]
new[j[1],j[0]]=a[i]
戻る:
array([[ 11., 12., 13.],
[ 12., 22., 23.],
[ 13., 23., 33.]])
これを達成するためのより良い方法はありますか?具体的には、Python ループを回避して 2D 配列を再構築しますか?