Search code examples
performancematlabmaxmin

Is min(A,[],"all") or min(A(:)) more efficient?


In matlab, which is more efficient, min(A,[],"all") or min(A(:))?

A is a 200x200 matrix. My first idea is that min(A,[],"all") should be faster. Because A(:) will expand the matrix. Is there anyone can interpret these results?

enter image description here

The code is below:

rng(1)
res=rand(200,200);

timeitn= 100; %10000000
tic
for i=1:timeitn
    min(res,[],"all");
end
toc

tic
for i=1:timeitn
    min(res(:));
end
toc

Solution

  • The nearly half a second time difference you measured is likely caused by other stuff going on in your computer during the measurement. Use timeit for a more precise time measurement.

    Or, it could have been caused by the more extensive input argument validation that is necessary to interpret ([],"all") in the first case.

    Either way, I don’t expect these two forms to be significantly different in cost. The operation A(:) is essentially free, since no data is copied. This operation simply creates a new array with a different size that points to the same data as A.