omit for-loop per arrayfun function

1 visualizzazione (ultimi 30 giorni)
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 Commenti
Rik
Rik il 17 Ago 2020
Why do you want to replace the for loop with arrayfun?
Alejandro Fernández
Alejandro Fernández il 18 Ago 2020
To try to reduce the time as much as possible since in a real case the size of the loop exceeds 4000 iterations

Accedi per commentare.

Risposta accettata

Rik
Rik il 18 Ago 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

Più risposte (0)

Categorie

Scopri di più su Programming in Help Center e File Exchange

Prodotti


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by