Compute Average Matrix from Cell Array of Matrices
古いコメントを表示
I have a cell array of matrices of different sizes and constant length:
ABC = [(122x21) (124x21) (117x21)....]
I would like to create a new matrix, where each element contains the average of each element from each of my array matrices.
NewMat = (124x21)
where element (1,1) = mean of all of the 1,1 elements in my primary matrices element (1,2) = the mean of all of the 1,2 elements in my primary matrices
Edited to upload starting cell array
5 件のコメント
Azzi Abdelmalek
2014 年 12 月 3 日
your matrices are not the same size
Guillaume
2014 年 12 月 3 日
Please show a concrete example, so we can understand what you want to do.
For example, given:
ABC = {[1 2;3 4;5 6; 7 8], [10 11; 12 13], [20 21; 22 23; 24 25]};
What would NewMat be?
Mat
2014 年 12 月 3 日
Thorsten
2014 年 12 月 3 日
Then you need to modify Azzi's solution, I think, that would return 8/3 in the above example.
採用された回答
その他の回答 (3 件)
The idea is to create a 124x21xN matrix 'Anew' with missing values filled with NaNs, and then take the nanmean along the third dimension of 'Anew':
A = {rand(122,21), rand(124,21), rand(117,21)};
[nrows ncols] = cellfun(@size, A);
if any(ncols - 21)
error('Not all arrays have 21 columns.')
end
maxrows = max(nrows);
for i = 1:numel(A)
X = A{i};
if size(X, 1) < maxrows
X(maxrows, 21) = NaN;
end
Anew(:,:,i) = X;
end
M = nanmean(Anew, 3);
Guillaume
2014 年 12 月 3 日
You don't have a cell array of matrices, but a cell array of cell arrays that should be matrices:
This will work (based on Azzi's answer):
maxrows = max(cellfun(@(c) size(c, 1), ABC3));
numcols = cellfun(@(c) size(c, 2), ABC3);
assert(all(diff(numcols) == 0)) %just make sure
resized = cellfun(@(c) [cell2mat(c); NaN(maxrows-size(c, 1), numcols(1))], ABC3, 'UniformOutput', false);
out = nanmean(cat(3, resized{:}), 3)
2 件のコメント
Mat
2014 年 12 月 3 日
Guillaume
2014 年 12 月 3 日
ABC4 = cellfun(@(c) cell2mat(c), 'UniformOutput', false);
It's the individual cells in the main cell array that you want to convert to matrices, not the main cell array.
My code does just the above ( cell2mat) when it comes to resize the matrix to match the maximum height.
カテゴリ
ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!