2013-02-05 156 views
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] 

我想從在上述矩陣中的每一行向量中減去平均行向量(RAV)(M) 即M(i)-rav。 我怎樣才能以有效的方式做到這一點?

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

這緣於broadcasting工作:

回答

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矩陣和相當昂貴。

1

假設你正在使用numpy的,因爲這是這麼簡單。

如果你使用普通的列表,這是一個有點複雜,它的代碼就會慢很多,但這樣的事情應該這樣做:

# 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] 
+0

非常感謝。有用。另一件事,我如何有效地規範每行vecor。我將每行矢量除以每個矢量的長度。 – user1964587