Thoth
Thoth

Reputation: 1041

Find maximum of each cell array element efficiently

We have foe example a 3x5 cell array where each element is a matrix. Can we find the maximum of each cell element, i.e, a matrix, and store the corresponding value in a new 3x5 matrix? All this without for loops. Bellow there is the naive way.

Example:

a = rand(5,6);
b = rand(7,6);
c = rand(7,9);
d = rand(27,19);
CellArray = cell(2,2);
CellArray{1}=a;
CellArray{2}=b;
CellArray{3}=d;
CellArray{4}=c;

MaxResults = nan(size(CellArray));
for i=1:numel(size(CellArray))
    MaxResults(i) = max(max(CellArray{i})); 
end

Thank you.

Upvotes: 1

Views: 4026

Answers (1)

Jonas
Jonas

Reputation: 74930

Not guaranteed to be that much more efficient (until Matlab decides to multithread it), but you can use cellfun like this:

MaxResults = cellfun(@(x)max(x(:)), CellArray)

Upvotes: 7

Related Questions