N=10000;
v=randi(50,N,1);
if~isequal(fun_deliberately_slow(v),fun_fast(v)) || ...
~isequal(fun_deliberately_slow(v),fun_hidden_loop(v))
error('functions don''t match')
else
clc
fprintf('loop : %.6f seconds\n',...
timeit(@()fun_deliberately_slow(v)))
fprintf('arrayfun: %.6f seconds\n',...
timeit(@()fun_hidden_loop(v)))
fprintf('direct : %.6f seconds\n',...
timeit(@()fun_fast(v)))
end
function a=fun_deliberately_slow(v)
a=zeros(size(v));
for n=1:numel(v)
a(n)=sum(v(1:n));
end
end
function a=fun_hidden_loop(v)
n=(1:numel(v))';
a=arrayfun(@(n) sum(v(1:n)),n);
end
function a=fun_fast(v)
a=cumsum(v);
end
2 Comments
Direct link to this comment
https://au.mathworks.com/matlabcentral/answers/580905-omit-for-loop-per-arrayfun-function#comment_976503
Direct link to this comment
https://au.mathworks.com/matlabcentral/answers/580905-omit-for-loop-per-arrayfun-function#comment_976503
Direct link to this comment
https://au.mathworks.com/matlabcentral/answers/580905-omit-for-loop-per-arrayfun-function#comment_976833
Direct link to this comment
https://au.mathworks.com/matlabcentral/answers/580905-omit-for-loop-per-arrayfun-function#comment_976833
Sign in to comment.