I have a function fun that returns a double. I want to call the function n times and store the results in an array:
results = zeros(1, n);
for i = 1:n
results(i) = fun;
end
Can I achieve this without the loop?
n is in a range of up to 10,000,000, the runtime of fun is almost neglectable.
I tried arrayfun, but it is actually a lot slower (about 87 times slower):
results = arrayfun(@(~) fun, 1:n);
May the loop already be the fastest solution? I’d still be interested if this could be done with a one liner.
First, know that ARRAYFUN basically has a hidden for-loop inside it, so I am not sure you will gain speed. Plus the good old for-loop can sometimes benefit from the Just-in-Time compiler optimizations, so stick with loops 🙂
If you really want to optimize your code, write your Java function to return an array of n elements at once, rather than calling from MATLAB n times each time returning one value (the bottleneck is the call overhead here).