Averaging Together Every N Columns

Hi!
I have a 16:10000 matrix (positive and negative decimal values) and want to reshape it to a 16:10 matrix by averaging each row every 1000 columns. What's the best way to do this?
Thanks very much! SE

 採用された回答

the cyclist
the cyclist 2014 年 4 月 10 日

2 投票

This solution using the filter() command calculates interim results way beyond your need, but it's fast:
% Put in some pretend data
r = rand(16,10000);
% Define number of columns to average
AVG_COLS = 1000;
% Dimension over which to average
DIM = 2; % Columns
% Use filter to calculate the moving average across EVERY combination of columns
r_moving_avg = filter(ones(1,AVG_COLS)/AVG_COLS,1,r,[],DIM);
% Grab only the column averages that were actually wanted
r_avg = r_moving_avg(:,AVG_COLS:AVG_COLS:end)

その他の回答 (3 件)

Jan
Jan 2014 年 4 月 10 日
編集済み: Jan 2014 年 4 月 10 日

1 投票

r = rand(16, 10000);
s = reshape(r, 16, 1000, 10);
t = squeeze(mean(s, 2));
Some timings:
r = rand(16, 10000);
tic;
for k = 1:20
AVG_COLS = 1000;
DIM = 2; % Columns
r_moving_avg = filter(ones(1,AVG_COLS)/AVG_COLS,1,r,[],DIM);
r_avg = r_moving_avg(:,AVG_COLS:AVG_COLS:end);
end
toc
tic;
for k = 1:20
N = 1000 ;
szA = size(r) ;
B = arrayfun(@(k) mean(r(:,k:min(szA(2),k+N-1)),2), 1:N:szA(2), 'un', 0) ;
B = [B{:}] ;
end
toc
tic;
for k = 1:20
s = reshape(r, 16, 1000, 10);
t = squeeze(mean(s, 2)); end
toc
Elapsed time is 1.671149 seconds.
Elapsed time is 0.035495 seconds.
Elapsed time is 0.016600 seconds.
Sarah
Sarah 2014 年 4 月 10 日

0 投票

Thanks so much - works like a charm!
Jos (10584)
Jos (10584) 2014 年 4 月 10 日

0 投票

Another option:
A = rand(16,10000) ;
N = 1000 ;
szA = size(A) ;
B = arrayfun(@(k) mean(A(:,k:min(szA(2),k+N-1)),2), 1:N:szA(2), 'un', 0) ;
B = [B{:}] ;

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

2014 年 4 月 10 日

編集済み:

Jan
2014 年 4 月 10 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by