omit for-loop per arrayfun function
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Rik
2020-8-18
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
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!