Search code examples
matlabcell-array

How to return the index of a cell which holds the largest valued element of a given column


Lets say we have Q cells, and each cell holds a N x M array. Where Array{q}(n,m) is the element in the nth row of the mth column of the qth cell.

I want to find the index of the cell that holds the greatest value element in each column.

Can anyone suggest a simple way to do this?


Solution

  • I would concatenate your cell array into a 3D matrix, and then use max to find the maximum value of each column and then use max to again find the maximum value along the third dimension and use the second output of max to indicate which cell it belongs to

    % Convert data into 3D array
    condensed = cat(3, Q{:});
    
    % Find the location in the maximum
    [~, ind] = max(max(condensed, [], 1), [], 3);
    

    And as an example:

    Q = {[2 1; 
          4 0], ...
    
         [1 2; 
          3 1]};
    
    [~, ind] = max(max(cat(3, Q{:}), [], 1), [], 3);
    %   1   2