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
Rik 2020-8-17
Why do you want to replace the for loop with arrayfun?
Alejandro Fernández
To try to reduce the time as much as possible since in a real case the size of the loop exceeds 4000 iterations

请先登录,再进行评论。

采纳的回答

Rik
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 个)

类别

Help CenterFile Exchange 中查找有关 Elementary Polygons 的更多信息

产品


版本

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by