Vectorizing evaluation of cell array of functions

2 ビュー (過去 30 日間)
Tristan Potter
Tristan Potter 2019 年 9 月 18 日
コメント済み: Bruno Luong 2019 年 9 月 19 日
I have an S-by-1 cell array of function handles, each taking one argument---call it 'funcell'. I also have an S-by-1 vector of numeric values---call it 'inputs'. My goal is to obtain a numeric vector of size S-by-1---call it 'output', such that each element j of 'output' contains the corresponding function evaluated at the corresponding numeric value.
In a for loop, this would just be:
for j=1:S
output(j)=funcell{j}(inputs(j))
end
The problem is that S is very large, so this is slow. Is there a way to vectorize this process for speed?
  1 件のコメント
Bruno Luong
Bruno Luong 2019 年 9 月 19 日
編集済み: Bruno Luong 2019 年 9 月 19 日
"The problem is that S is very large, so this is slow. Is there a way to vectorize this process for speed?"
This is again a wrong preconceived slowness of FOR-LOOP. It is slow because you evaluate many function handles not because it is embeded in a FOR-LOOP.

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

回答 (1 件)

James Tursa
James Tursa 2019 年 9 月 18 日
編集済み: James Tursa 2019 年 9 月 18 日
Not sure this will be any faster since the loop is just hidden, but you can try this:
output = arrayfun(@(x,y)x{1}(y),funcell,inputs);
Did you pre-allocate output before your loop? I'm assuming your example was a typo and was supposed to read:
output(j)=funcell{j}(inputs(j))
  2 件のコメント
Tristan Potter
Tristan Potter 2019 年 9 月 18 日
Thanks for the suggestion---it yields a modest speed-up, but computation is still pretty slow.
And yes, that was a typo. I've edited the original post accordingly.
Bruno Luong
Bruno Luong 2019 年 9 月 19 日
It yields a modest speed-up
Expected, because the slowness is NOT due to the for-loop.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by