Sparkler
Sparkler

Reputation: 2913

Which should I use in MATLAB: max(A(:)) or max(max(A))?

I get a pretty consistent time difference for small matrices in favor of max(A(:)):

>> A=rand(100); tic; max(A(:)); toc; tic; max(max(A)); toc;
Elapsed time is 0.000060 seconds.
Elapsed time is 0.000083 seconds.

but for large matrices, the time difference is inconsistent:

>> A=rand(1e3); tic; max(A(:)); toc; tic; max(max(A)); toc;
Elapsed time is 0.001072 seconds.
Elapsed time is 0.001103 seconds.
>> A=rand(1e3); tic; max(A(:)); toc; tic; max(max(A)); toc;
Elapsed time is 0.000847 seconds.
Elapsed time is 0.000792 seconds.

same for larger,

>> A = rand(1e4); tic; max(A(:)); toc; tic; max(max(A)); toc;
Elapsed time is 0.049073 seconds.
Elapsed time is 0.050206 seconds.
>> A = rand(1e4); tic; max(A(:)); toc; tic; max(max(A)); toc;
Elapsed time is 0.072577 seconds.
Elapsed time is 0.060357 seconds.

Why is there a difference and what would be the best practice?

Upvotes: 1

Views: 144

Answers (2)

patrik
patrik

Reputation: 4558

As horchler says this is machine dependent. However, on my machine I saw a clear performance decrease for the max(max(max(... for higher dimensions. I also saw a slight (but consistent) advantage in speed for max(A(:)) for a more sorted type o matrix as the toeplitz matrix. Still, for the test case that you tried I saw hardly any difference.

Also max(max(max(... is error prone due to all the paranthesis I would prefer the max(A(:)). The execution time for this function seems to be stable for all dimensions, which means that it is easy to know how much time this function takes to execute.

Thirdly: The function max seems to be very fast and this mean that the performance should be a minor issue here. This means that max(A(:)) would be preferred in this case for its readability.

So as a conclusion, I would prefer max(A(:)), but if you think that max(max(A)) is clearer you could probably use this.

Upvotes: 3

Sam Roberts
Sam Roberts

Reputation: 24127

On my machine there are no differences in times that are really worth worrying about.

n = 2:0.2:4;
for i = 1:numel(n)
    a = rand(floor(10^n(i)));
    t1(i) = timeit(@()max(a(:)));
    t2(i) = timeit(@()max(max(a)));
end

>> t1
t1 =
  Columns 1 through 7
   7.4706e-06   1.5349e-05   3.1569e-05    2.803e-05   5.6141e-05   0.00041006    0.0011328
  Columns 8 through 11
    0.0027755     0.006876       0.0171     0.042889
>> t2
t2 =
  Columns 1 through 7
   1.1959e-05   2.2539e-05   2.3641e-05   4.1313e-05   7.6301e-05   0.00040654    0.0011396
  Columns 8 through 11
    0.0027885    0.0068966      0.01718     0.042997

Upvotes: 2

Related Questions