0

假设矩阵为 M=

[[.10, .32, .20, .40, .80], 
 [.23, .18, .56, .61, .12], 
 [.90, .30, .60, .50, .30], 
 [.34, .75, .91, .19, .21]]

平均行向量是 rav=

[ 0.3925  0.3875  0.5675  0.425   0.3575]

我想从上述矩阵 (M) 中的每个行向量中减去平均行向量 (rav),即 M(i)-rav。我怎样才能以有效的方式做到这一点?

4

2 回答 2

1

假设您使用的是 numpy,这很简单:

M = np.asarray(M) # make sure M is an array...it presumably would be
rav = np.mean(M, axis=0)
diffs = M - rav

由于广播而起作用。

如果您使用的是普通列表,它会稍微复杂一些,并且代码会慢得多,但是应该这样做:

# M is a list of num_rows lists of num_cols floats
rav = [sum(row[j] for row in M) / num_rows for j in range(num_cols)]
diffs = [[x - mean_x for x, mean_x in zip(row, rav)] for row in M]
于 2013-02-05T06:08:32.993 回答
1

在纯 Python 中

>>> [[i-j for i,j in zip(m, rav)] for m in M]
[[-0.2925, -0.0675, -0.3675, -0.024999999999999967, 0.44250000000000006], [-0.1625, -0.20750000000000002, -0.007499999999999951, 0.185, -0.2375], [0.5075000000000001, -0.08750000000000002, 0.03249999999999997, 0.07500000000000001, -0.057499999999999996], [-0.05249999999999999, 0.3625, 0.3425, -0.235, -0.1475]]

如果您正在执行一堆矩阵运算,使用 numpy 会更快。与 numpy 矩阵相互转换是相当昂贵的。

于 2013-02-05T06:11:43.173 回答