MATLAB: Max and Min values within vectors in a cell matrix and their indexes

cell arraysmaximumminimum

Hi, Some days ago I asked a question that fortunately was answered http://mathworks.com/matlabcentral/answers/14423-max-and-min-values-within-vectors-in-a-cell-matrix. Now I'd like to add an extension to this problem. Using the code provided in that answer:
N = size(C,1);
out = zeros(N,2);
for i1 = 1:N
p1 = [C{i1,:,:}];
out(i1,:) = [min(p1) max(p1)];
end
I'd like to get in which cell the max and min values are observed. That is, in the Nx865x351 cell matrix, for each N, I want to know where the found max/min values occur. Each cell has a variable length vector from empty vector up to 12 values. Thanks in advance for your help!

Best Answer

use [Y,I]=max(x) to return the maximum value and index.
Assume every cell is a nx1 or 1xn array or empty.
C=cell(3,4,5);
C(:)={0};
C{1,2,3}=[];
C{2,3,4}=1:12;
% need to process empty cells
Index=cellfun('isempty',C);
C(Index)={NaN};
M=cellfun(@max,C,'uni',false);
[Value,Index]=max([M{:}]);
[x,y,z]=ind2sub(size(C),Index)