How to compute the mean of several matrices in a cell?

조회 수: 1 (최근 30일)
Kim Arnold
Kim Arnold 2020년 9월 30일
댓글: Kim Arnold 2020년 9월 30일
I have 15 matrices (size of each matrix 17x5000) in a type of cell named M_one and size 1x15 {1,15] (matrix 1 would be M_onel{1,1}, matrix 2 would be in M_one{1,2} and so on. I want to sum together always 3 matrices and then calculate the mean of those three matrices. This would look like:
M_onel{1,1}+M_one{1,2} + M_one{1,3}./3 % sum first three matrices and calculate mean by dividing with 3
M_onel{1,4}+M_one{1,5} + M_one{1,6}./3 % same for matrices 4,5 and 6
M_onel{1,7}+M_one{1,8} + M_one{1,9}./3 % same for matrices 7,8 and 9
... % same for matrices 10,11,12 and 13,14, 15
Is there an easier way to do it, for example in a loop? Since I want it to do always for 3 matrices its not easy to do it with a loop.
Thanks already in advance for your help!

채택된 답변

Stephen23
Stephen23 2020년 9월 30일
편집: Stephen23 2020년 9월 30일
Just for fun, if your memory can handle it:
A = mean(permute(cell2mat(reshape(M_one,1,1,3,[])),[1,2,4,3]),4)
For matrices of that size, a loop will be most efficient, e.g.:
M_one = arrayfun(@(n)randi(17,5000),1:15,'uni',0); % fake data
C = reshape(M_one,3,[]);
N = size(C,2);
D = cell(1,N); % preallocate
for k = 1:N
D{k} = mean(cat(3,C{:,k}),3);
end
  댓글 수: 1
Kim Arnold
Kim Arnold 2020년 9월 30일
Thanks a lot for this nice answer. I prefer the second option, I think my memory was a bit exhausted :)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 9월 30일
An alternative approach. M_one is your 1x15 cell array
M_one = mat2cell(M_one, 1, 3*ones(1, numel(M_one)/3));
M_avg = cellfun(@(x) {mean(cat(3, x{:}), 3)}, M_one);

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by