omit for-loop per arrayfun function
1 view (last 30 days)
Show older comments
Alejandro Fernández
on 17 Aug 2020
Commented: Alejandro Fernández
on 18 Aug 2020
Hello, let's see if someone could help me, starting from a BB matrix of dimensions m X 8 and containing the X and Y positions of the vertices of a rectangle by rows I need to convert each row of that matrix into a polygon and then apply polybuffer with an offset of 1. I know how to do it with a for loop. Would there be any way to use arrayfun to get the same result?
for i = 1 : size(BB,1)
pgonBB{i,1} = polyshape(BB(i,1:2:8),BB(i,2:2:8),'Simplify',false);
pgonBB{i,1} = polybuffer(pgonBB{i,1},offset,'JointType','miter','MiterLimit',2);
end
2 Comments
Accepted Answer
Rik
on 18 Aug 2020
I doubt arrayfun will cause the speed-up you're hoping for. It has its own overhead, so it might even be slower. Functions like rowfun, cellfun and arrayfun only hide the loop, they don't remove it. The real speed-up is when you move to array operations.
The example below shows an example in action.
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)
%essentially the same code as the loop above
n=(1:numel(v))';
a=arrayfun(@(n) sum(v(1:n)),n);
end
function a=fun_fast(v)
a=cumsum(v);
end
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!