1

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.

4
  • Note that in your code you could replace max(max(CellArray{i})) by max(CellArray{i}(:)) (as in @Jonas's answer), which is probably faster Commented Jan 30, 2014 at 11:28
  • 1
    Also I highly doubt you want your loop to go to numel(size(CellArray)) but rather to just numel(CellArray) Commented Jan 30, 2014 at 11:37
  • Yes you are right Dan. Commented Jan 30, 2014 at 11:42
  • 1
    @LuisMendo: max(max(CellArray{i})) is actually faster than max(CellArray{i}(:)) for large inputs. Commented Jan 30, 2014 at 11:48

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.