フィルターのクリア

omit for-loop per arrayfun function

1 回表示 (過去 30 日間)
Alejandro Fernández
Alejandro Fernández 2020 年 8 月 17 日
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
Alejandro Fernández 2020 年 8 月 18 日
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
  1 件のコメント
Alejandro Fernández
Alejandro Fernández 2020 年 8 月 18 日
Ah okey, thank you so much for all your help!!!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeElementary Polygons についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by