0

For example, would

raw = ones(1000, 1);
x = cell(1000, 1);
for i=1:size(raw, 1)
    x(i) = some_process(raw(i));
end

require more memory than

raw = ones(1000, 1);
x = arrayfun(@(r) some_process(r), raw, 'UniformOutput', False);

As far as my understanding goes, the pre-allocated for-loop would require initialization of both raw and x before beginning the process thus requiring more memory overall. Is this correct?

Thank you for your help.

1 Answers1

4

No, it is not more efficient, and in some cases may even perform worse. arrayfun is basically just syntactic sugar for a for loop. Matlab's JIT is able to optimize "in-place" modifications of preallocated arrays. I have not encountered any cases where arrayfun() used with a function handle performs better than a for loop and preallocated arrays on recent-ish versions of Matlab.

In your particular case, they're likely to perform about the same. So use whichever style you prefer.

Note that, strictly speaking, arrayfun does not perform "vectorized" operations. "vectorized" refers to some built-in Matlab facility that is able to operate on a whole array inside the Matlab engine, using . arrayfun isn't able to magically do that.

Exception: if you are using the Matlab Parallel Computing Toolbox, or are operating on tall arrays, then arrayfun actually can parallelize operations across multiple array elements, and may go faster than a for loop.

Andrew Janke
  • 23,508
  • 5
  • 56
  • 85
  • Thank you so much, this is a great answer. Could I essentially say that for loops are the way to go unless parallelization is a requirement - as they're faster and perform similarly on memory to arrayfun? – AYUSH LALL Jun 19 '20 at 21:06
  • Yes. :) And they're more readable, too, in my opinion. – Andrew Janke Jun 19 '20 at 21:27