average between cell arrays of doubles
5 ビュー (過去 30 日間)
古いコメントを表示
Hello, I'm working with a nested cell array in which each original cell contains a nested cell array of doubles.
For simplicity, the original nested array could have 10 cell arrays within it. For each of those cell arrays, there are 100 doubles that are 30x50 in length. I would like to get the mean/average of all of those doubles such that they go from 100 instances of 30x50 doubles to just 1 single instance of 30x50 double.
This would result with the average value found in each element of the double across the instances. This would mean that the original cell array is now 10 cells, with each having only one instance of 30x50 double as their individual averages.
Please let me know if you need more information to help me with calculating the average. Thank you!
0 件のコメント
採用された回答
Voss
2024 年 6 月 10 日
C_mean = cellfun(@(c)mean(cat(3,c{:}),3),C,'UniformOutput',false);
5 件のコメント
Voss
2024 年 6 月 10 日
You're welcome!
It wasn't clear to me from your code whether D or cMat was the cell array you described in the question. (I guess D because each cell of cMat contains a matrix instead of a cell array.) If D is the relevant cell array, then the cellfun code from my answer should be placed after the mtemp loop, because it is intended to operate on a cell array of cell arrays. But it can't operate on D, since what you really want to operate on is a cell array that contains the padded versions of the contents of D, which is all values of cMat across all iterations of the mtemp loop, so you'd have to construct that - below I call it C. Something like this:
% create random D
% 10-by-1 cell array, each cell containing a 100-by-1 cell array,
% each cell of that containing a 30x50 double matrix
D = cell(10,1);
for ii = 1:10
D{ii} = permute(num2cell(rand(30,50,100),[1 2]),[3 1 2]);
end
%preallocate C
C = cell(size(D,1),1);
for mtemp = 1:size(D,1)
c = D{mtemp,1};
numCol = cellfun(@(x) size(x,2), c);
maxNumCol = max(numCol); % max number of columns
numColToAdd = maxNumCol-numCol;
%preallocate cMat
cMat = cell(size(c,1),1);
for padtemp = 1:size(c,1)
% pad with NaNs
cMat{padtemp} = padarray(c{padtemp},[0,numColToAdd(padtemp)],NaN,'Post');
end %padtemp
% pause
C{mtemp} = cMat;
end %mtemp
%calculate mean
C_mean=cellfun(@(c)mean(cat(3,c{:}),3,'omitnan'),C,'UniformOutput',false)
I simplified the padding code because it's not necessary to use cell2mat and cellfun for that; since c{padtemp} is a matrix you can call padarray on it directly and store the result in a cell of cMat.
It's possible that code still may not work for you, in which case please save the variable D to a mat file and upload the mat file here and I'll take a look at it.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!