Replacing arrayfun with for loop
4 次查看(过去 30 天)
显示 更早的评论
Is there already a function that does what arrayfun does, but with a for loop?
In other words, is there a way to call a function on each element in an array using a for loop and output the values to a vector of cell arrays?
I am looking for something like:
outputvector = myforloopfunction(functionhandle(inputvector), 'UniformOutput', false)
I think this approach would be faster than use of the arrayfun, which is only faster than for loops on GPU, but not CPU.
Thank you.
3 个评论
Jan
2012-11-2
编辑:Jan
2012-11-2
@Justin: Sven is right: The line of code is not useful. I guess you mean:
output = myforloop(functionhandle, input1, input2)
@Sven: CELLFUN is really slow with anonymous functions. NUM2CELL and CELL2MAT are not really efficient also. Therefore I assume that the "in = ..." line is a hot spot of your implementation. Please run this (I cannot do it by myself, currently):
function out = testme(fcn, arg1, arg2)
out = cell(size(arg1));
for ii = 1:numel(out)
out{ii} = fcn(arg1(ii), arg2(ii));
end
Timings:
in1 = rand(400,1); % Do not shadow the builin "input"
in2 = in1 * 2; % Outside the tic-toc
tic, for k = 1:1000, arrayfun(@plus, in1, in2,'Un',0); end, toc
tic, for k = 1:1000, testme(@plus, in1, in2); end, toc
Sven
2012-11-2
编辑:Sven
2012-11-2
@Jan:
I agree completely about the slow bits - cellfun and wrapping/unwrapping arrays into cells will be a big overhead. Mine was a half-hearted attempt at making testme() take in an arbitrary number of parameters (like arrayfun does). That's why I asked Justin for an example - if we know exactly how many arguments we have, then like in your example (with 2 hard-coded arguments), we can index directly into those arrays. Here's how your code timed on my machine:
tic, for k = 1:1000, arrayfun(@plus, in1, in2,'Un',0); end, toc
tic, for k = 1:1000, testme(@plus, in1, in2); end, toc
Elapsed time is 0.902931 seconds.
Elapsed time is 1.570489 seconds.
Justin, this is closer to arrayfun() than my more generalised solution, but arrayfun still wins the race. I suggest you'll only get faster performance than arrayfun() in particular situations - ie, there won't be any general solution that you can code into a function that always gets faster performance than arrayfun.
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!