如何逐块平均列?

时间:2014-09-21 21:26:25

标签: matlab matrix average

比方说,我有以下矩阵:

[1 2 3 4 1 2 3 4

1 2 3 4 1 2 3 4

1 2 3 4 1 2 3 4]

我怎么能以编程方式将每四列的平均值放在一起,以便最终得到结果 用:

[2.5 2.5

2.5 2.5

2.5 2.5]

谢谢,

汤姆

3 个答案:

答案 0 :(得分:3)

使用reshape

可以不使用循环
A = [1 2 3 4 1 2 3 4
     1 2 3 4 1 2 3 4
     1 2 3 4 1 2 3 4]; %// data matrix
N = 4; %// number of columns to average
result = squeeze(mean(reshape(A,size(A,1), N, []), 2));

如果您有图像处理工具箱,还可以使用blockproc

result = blockproc(A, [size(A,1) N], @(x) mean(x.data, 2))

答案 1 :(得分:3)

基于sumreshape -

的一种方法
reshape(sum(reshape(A,size(A,1),N,[]),2)/N,size(A,1),[])

此处介绍了迄今为止发布的解决方案的一些基准。

基准代码 -

m = 1000; %// No. of rows in input
n = 4000; %// No. of cols in input
A = rand(m,n); %// Input with random data
N = 4; %// number of columns to average;
num_runs = 200; %// No. of iterations

disp('----------------- With sum+reshape');
tic
for k1 = 1:num_runs
    out1 = reshape(sum(reshape(A,size(A,1),N,[]),2)/N,size(A,1),[]);
end
toc,clear out1

disp('----------------- With mean+reshape');
tic
for k1 = 1:num_runs
    out2 = squeeze(mean(reshape(A,size(A,1), N, []), 2));
end
toc,clear out2

disp('----------------- With blockproc');
tic
for k1 = 1:num_runs
    out3 = blockproc(A, [size(A,1) N], @(x) mean(x.data, 2));
end
toc,clear out3

disp('----------------- With filter');
tic
for k1 = 1:num_runs
    B = filter(ones(1,N)/N,1,A,[],2);
    out4 = B(:,N:N:end);
end
toc,clear out4 B

结果 -

----------------- With sum+reshape
Elapsed time is 4.011844 seconds.
----------------- With mean+reshape
Elapsed time is 3.945733 seconds.
----------------- With blockproc
Elapsed time is 59.018457 seconds.
----------------- With filter
Elapsed time is 31.220875 seconds.

答案 2 :(得分:2)

一种简单的方法是滥用filter

A = [1 2 3 4 1 2 3 4 ;
     1 2 3 4 1 2 3 4 ;
     1 2 3 4 1 2 3 4 ]

N = 4;

B = filter(ones(1,N)/N,1,A,[],2)
C = B(:,N:N:end)

给出:

C =

    2.5000    2.5000
    2.5000    2.5000
    2.5000    2.5000

这似乎比所有重塑和挤压动作快得多;)但没有证明。