1
votes

I have a cell array called template, where template is a 1x29 cell array. Each cell of template is a 14x10x31 matrix. Each element of the matrix is a double.

I want to find the mean 14x10x31 matrix of template i.e. I want a result which is a 14x10x31 matrix where e.g. element (1,1,1) of the result is the mean of all 29 values of (1,1,1) in the cell array template.

I'm not clear how to go about this.

I've looked at cellfun, and the options for the mean command i.e. how mean can be calculated across dimensions. For example, to calculate mean m across all three dimensions would be done as follows ...

m = cellfun(@(x) mean(mean(mean(x,1),2),3) , template, 'UniformOutput', false)

... which will give 1x29 cell array, each cell containing a single value i.e. the averaging together of all values in each 14x10x31 array, for each cell of the template variable.

But obviously this isn't what I want.

To achieve what I want do I need to convert (cell2mat?) the template variable to a matrix of 29x14x10x31 and then run mean on the first dimension of that? I've looked at reshape and cat too but I'm not clear how to put it all together though ... or if that is the best way to achieve what I want? Or can it / should it be done by using cellfun?

1

1 Answers

3
votes

The way to go is cell2mat, as you already remarked in the question. But simply applying cell2mat(A) will not work. As described in the MATLAB help, cell2mat keeps the underlying shape, as illustrated in the following image:

cell2mat (image by Mathworks)

In our case, that would create a matrix of size [14, 290, 31], as the cell array A is of size [1, 29]. If we simply reshape the cell array, such that it is in the fourth dimension, i.e. [1, 1, 1, 29], then the output of cell2mat will be [14, 10, 31, 29] and we can calculate the mean along the fourth dimension:

B = cell2mat(reshape(A,[1,1,1,size(A,2)]));
M = mean(B,4);