adding matrices inside a big matrix
2 次查看(过去 30 天)
显示 更早的评论
Hello everybody,
I am wandering if there is a way for not using loops to add many small matrices inside a big matrix. For example I have a big 40000x240000 matrix and I want to add all the numbers of 4x4 matrices inside that matrix, resulting in a 10000x60000 matrix.
thank you all for your answers
0 个评论
采纳的回答
Sean de Wolski
2011-11-15
And this fun answer:
sum4x4 = reshape(sum(reshape(reshape(sum(reshape(B,4,[])),size(B,1)/4,[])',4,[])),size(B)./4);
sum4x4 = reshape(sum4x4,size(sum4x4,2),size(sum4x4,1))'
where B is your matrix.
6 个评论
Sean de Wolski
2011-11-16
Good catch!
Just add this line will do the same thing.
sum4x4 = reshape(sum4x4,size(sum4x4,2),size(sum4x4,1))'
更多回答(3 个)
Fangjun Jiang
2011-11-15
Because the size of your matrix, you might want to re-use the matrix so replace the variable "e" and "f" with "d".
d=rand(40,24);
[M,N]=size(d);
e=mat2cell(d,4*ones(M/4,1),4*ones(N/4,1));
f=cellfun(@(x) sum(x(:)),e);
Sean de Wolski
2011-11-15
How about blkproc if you have the Image Processing Toolbox (or blockproc in newer versions).
blkproc(magic(16),[4 4], @(x)(sum(x(:))))
I'm surprised conversion to cell is faster than a well done for-loop. Perhaps you could post what you had for the nested for-loops?
4 个评论
Sean de Wolski
2011-11-15
in blkproc, did you change magic(16) to 'a'? the magic(16) was for demo purposes only.
Sean de Wolski
2011-11-15
Your for-loop could be sped up a little by building the j-index vectors outside of the k for-loop. Overall it's good though!
Andrei Bobrov
2011-11-17
e.g.
A = randi(25,12,16);
m = 4;
n = 4;
[M,N] = size(A);
out = reshape(sum(sum(reshape(A.',n,N/n,m,[]),3)),n,[])';
or
out2 = reshape(sum(sum(reshape(A,m,M/m,n,[]),3)),[],n);
or2
out3 = blockproc(A,[m n],@(block_struct)sum(block_struct.data(:)));
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Lighting, Transparency, and Shading 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!