2
$\begingroup$

For an expression like

Max @ Table[f[i, j], {i, 1, 1000}, {j, 1, 1000}]

does Mathematica first materialize the entire 1000x1000 matrix and then compute the max on it, or is it capable of rewriting the expressions so as to incrementally perform the reduction (the equivalent of using two nested for loops in an imperative language), needing only O(1) space?

If it only does the former, is there instead an alternate suggested approach to achieve result with O(1) space only (using two For constructs would work, but is quite clunky).

$\endgroup$
1
  • 3
    $\begingroup$ You might want to search mathematica.stackexchange for lazy and Google search for mathematica lazy. Those show a reasonable number of results describing methods to do lazy evaluation without constructing entire lists or tables before performing operations on them. You might be able to apply some of those results to your problem. $\endgroup$
    – Bill
    Oct 15, 2020 at 20:38

1 Answer 1

6
$\begingroup$

The answer to the question

does Mathematica first materialize the entire 1000x1000 matrix and then compute the max on it

is "Yes". Max does not hold its arguments, and so Max[foo] will first evaluate foo and then take its maximum.

The most straightforward way to compute the table maximum without storing all the values would be

max = -Infinity;
Do[max = Max[max, f[i, j]], {i, 1, 1000}, {j, 1, 1000}];
max
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.