Search code examples
matlabfor-loopmeancell-arrayvariance

How to apply function to each cell in a cell array which contains 3D Matrix in matlab?


I have a cell array A, of dimension say 1x8 and each cell consist of 10x13xNmatirx(numerical values).

Example:

10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double

now i want to take mean and variance for 10x13(130 Values) across N. i.e, (1,1,1)(1,1,2)...(1,1,N). first 2 values indicates the points and the third one refers to the position.

When i try to apply mean over a 1x8 Cell array of the same dimension and cell values as mentioned above using the cellfun function, i get the following error.

A = 1x8 cell

B = cellfun(@mean,A)

Error using cellfun Non-scalar in Uniform output, at index 1, output 1. Set 'UniformOutput' to false.

i need the results like only 260 values(mean+variance) across 8 elements of 1x8 Cellarray,by the way i can ignore the N values, since i take the mean and variance over N. How can i do this? Thanks.


Solution

  • Instead of using @mean, use @(x)mean(x,3), and as the others have mentioned - ...,'UniformOutput',false.

    Since the results of the computation always have the same size (10x13), you can convert the resulting cell to a numeric array, if you reshape B to be a vector in the 3rd dimension:

    C = cell2mat(reshape(B,1,1,[]));
    

    Now, if you also want to compute variance while you're at it, you can do something like

    B = cellfun(@(x)cat(3,mean(x,3),var(x,0,3)),A,'UniformOutput',false);
    

    But if you want this last B as a numeric array, you'd need to make it a vector in the 4th dimension (since the 3rd was taken by the concatenation):

    C = cell2mat(reshape(B,1,1,1,[]));