根据不同大小的索引计算平均数据

时间:2014-11-14 10:39:43

标签: matlab

我需要计算归一化到某个事件(时间0)的随时间变化的平均值。 第一栏=时间 第二列=感兴趣的数据

A = [ -5 1 ; -4 2 ; -3 3 ; -2 4 ; -1 5 ; 0 6 ; 1 7 ; 2 8 ; 3 9 ; 4 10 ; 5 11 ];   

B = [ -3 7 ; -2 6 ; -1 5 ; 0 4 ;1 3 ; 2 2 ; 3 1 ];

结果应该像 C = [-5 NaN; -4 NaN; -3 5; -2 5; -1 5; 0 5; 1 5; 2 5; 3 5; 4 NaN; 5 NaN];

我已将所有数据放在一个矩阵中,以便B部分的末尾用零填充。我想过使用find找到最长列的索引,而不是找到索引所在的所有列+1的均值。还没有工作。

我怎么能这样做,因为数据的长度和索引不一样? 谢谢,Stefan

2 个答案:

答案 0 :(得分:2)

使用accumarray anonymous function的任意数量矩阵的通用解决方案:

A = [ -5 1 ; -4 2 ; -3 3 ; -2 4 ; -1 5 ; 0 6 ; 1 7 ; 2 8 ; 3 9 ; 4 10 ; 5 11 ];
B = [ -3 7 ; -2 6 ; -1 5 ; 0 4 ;1 3 ; 2 2 ; 3 1 ];
matrices = {A, B}; %// put here as many matrices as needed
M = vertcat(matrices{:});
n = numel(matrices);
result = accumarray(M(:,1)-min(M(:,1))+1, M(:,2), [],...
    @(x) mean([x; NaN(n-numel(x),1)]), NaN);

这假设如果所有矩阵在第一列中都缺少一个中间值,那么您还希望填充NaN。如果您想跳过这些值,可以使用

result = accumarray(M(:,1)-min(M(:,1))+1, M(:,2), [],...
    @(x) mean([x; NaN(n-numel(x),1)]), inf);
result = result(~isinf(result));

答案 1 :(得分:1)

您可以使用以下代码:

[~,i1,i2] = intersect(A(:,1),B(:,1));
B_temp = [A(:,1) nan(size(A,1),1)];
B_temp(i1,:) = B(i2,:);
C = [A(:,1) mean([A(:,2) B_temp(:,2)],2)];

您可以使用想要的插值,但对于两个数据点,mean应该没问题。输出是:

C =

    -5   NaN
    -4   NaN
    -3     5
    -2     5
    -1     5
     0     5
     1     5
     2     5
     3     5
     4   NaN
     5   NaN