Search code examples
matlabcell-array

Cell functions for nested cell arrays in Matlab


I would like to know if it is possible to use cell functions in nested cell arrays.

Let's say I have a 3x3 cell array AB, each element of which is again a 3x3 cell array and each element of which is then for example a 3x3 matrix.

   A=cell(3,3);
   AB=A;
   for i=1:1:3
      for j=1:1:3
          AB{i,j}=cell(3,3)
      end
   end

If I then want to do an operation in each matrix, and thus in each element of each element of the cell array (sorry it sounds horrible), how would it work?

An example would be, if you want to build the sum of the matrix rows, with something like this...

    AB2=cellfun(@sum,AB);

or

    AB2=cellfun(@sum,AB{:,:});

But this doesn't work. I have tried multiple combinations with anonymous functions but they didn't work either. Is there a way to do this or do I need to put the cellfun in a loop?

I would appreciate your help.

Anna


Solution

  • cellfun will work if you have an unnested cell array, i.e. a single level of cells. For example, if you define your array as a 3×3×3×3 cell array of matrices you just need

    result = cellfun(@(x) sum(x,1), AB, 'uniformoutput', false);
    

    If you really need to do it a cell array of cell arrays of matrices, you can nest two cellfun. This will be slow:

    result = cellfun(@(ab) cellfun(@(x) sum(x,1), ab, 'uniformoutput', false), AB, 'uniformoutput', false);
    

    I'm using sum(x,1) to get the sum of each matrix column. If you want the sum of each row replace 1 by 2.