2011-01-11 126 views
1

我有一個10行乘20列的數組。每列對應於一個數據集,它不能與任何連續的數學函數(這是一系列實驗推導出來的數字)進行擬合。我想計算第4行和第8行之間每列的積分,然後將獲得的結果存儲在一個新數組(20行×1列)中。計算數據集範圍中積分的最有效方法

我試過使用不同的scipy.integrate模塊(例如quad,trpz,...)。

問題是,據我所知,scipy.integrate必須應用於函數,我不知道如何將我的初始數組的每列轉換爲函數。作爲替代方案,我考慮計算第4行和第8行之間每列的平均值,然後將此數字乘以4(即8-4 = 4,x間隔),然後將其存儲到我的最終20x1陣列中。問題是......呃......我不知道如何計算給定範圍內的平均值。我問的問題是:

  1. 哪種方法更高效/更簡單?
  2. 可以根據我所描述的數據集計算積分嗎?
  3. 如何計算一系列行的平均值?
+0

我可能失去了一些東西,而是一個整體的僅僅是區域中的「曲線」下,這樣你就可以只添加了值在每一列中。 – 2011-01-11 19:53:38

回答

2

要獲取的條目的總和爲4〜8(包括兩端)中的每一列,使用

a = numpy.arange(200).reshape(10, 20) 
a[4:9].sum(axis=0) 

(第一行是隻是以創建所需的形狀的示例性陣列。)

3

既然你只知道數據點,最好的選擇是使用trapz(基於你知道的數據點的梯形逼近積分)。

您很可能不想將您的數據集轉換爲函數,並且您不需要使用trapz

所以,如果我理解正確的話,你想要做這樣的事情:

from numpy import * 

# x-coordinates for data points 
x = array([0, 0.4, 1.6, 1.9, 2, 4, 5, 9, 10]) 

# some random data: 3 whatever data sets (sharing the same x-coordinates) 
y = zeros([len(x), 3]) 
y[:,0] = 123 
y[:,1] = 1 + x 
y[:,2] = cos(x/5.) 
print y 

# compute approximations for integral(dataset, x=0..10) for datasets i=0,1,2 
yi = trapz(y, x[:,newaxis], axis=0) 
# what happens here: x must be an array of the same shape as y 
# newaxis tells numpy to add a new "virtual" axis to x, in effect saying that the 
# x-coordinates are the same for each data set 

# approximations of the integrals based the datasets 
# (here we also know the exact values, so print them too) 
print yi[0], 123*10 
print yi[1], 10 + 10*10/2. 
print yi[2], sin(10./5.)*5. 
相關問題