Average every n*n elements in a two dimensional matrix

6 ビュー (過去 30 日間)
Peter
Peter 2013 年 5 月 10 日
I have a two dimensional matrix, and create a second matrix with the averages of every n*n elements. So, say I have a 100*100 matrix; I would want a 10*10 matrix where each single element is the average of the 10*10 elements in the original matrix at that location.
So far I have tried splitting the matrix into n separate row vectors, averaging each of those every n elements, concatenating and re averaging ever n of the averaged vectors. Then I concatenate each of those vectors. Is there a more efficient way to do this this, without using so many loops? It is very inefficient and inelegant for such a large matrix.
Thanks

採用された回答

Sean de Wolski
Sean de Wolski 2013 年 5 月 10 日
編集済み: Sean de Wolski 2013 年 5 月 10 日
If you have the Image Processing Toolbox, you can use blockproc
blockproc(magic(100),[10 10],@(bs)sum(bs.data(:)))
And for more info:
doc blockproc
Otherwise just use a double for-loop.
OR if you're curious to learn about vectorizing and speed is a top priority:
G = reshape(sum(reshape(sum(reshape(A,sz(1),blk(2),[]),2),blk(1),[]),1),sz./blk);
And broken into pieces:
A = magic(100);
blk = [10 10];
sz = size(A);
B = reshape(A,sz(1),blk(2),[]); %reshape so every blk column is a page
C = sum(B,2); %sum blocks across rows
D = reshape(C,blk(1),[]); %reshape so each column is a block
E = sum(D,1); %sum columns
F = reshape(E,sz./blk); %reshape to final size.
  1 件のコメント
Peter
Peter 2013 年 5 月 10 日
Yes, that's perfect. That give the sum of those elements, and to get the mean I just divided by the number of elements.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeComputer Vision with Simulink についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by