How to avoid using for loops when declaring functions in a cell array

In my source codes:
clear all
fout=cell(1,10);
B=zeros(10,20);
for ii=1:1:10
fout{ii}=@(x) 2*pi*x*(1:1:20)+ii;
end
for ii=1:1:10
B(ii,:)=fout{ii}(2);
end
display(B);
How can I use the matlab vectorization to declare functions in a cell array as well as to provide function outputs in one go rather than using two for loops? M

回答 (1 件)

Adam Danz
Adam Danz 2020 年 9 月 11 日
編集済み: Adam Danz 2020 年 9 月 11 日

0 投票

You only need 1 anonymous function if you include ii as a second input. ii must be a column vector and x must be a row vector.
fout = @(x,ii) 2*pi*x*(1:1:20)+ii;
B = fout(2,(1:10)');
Alternatively, the 2nd loop in your question can be replaced by
y = cell2mat(arrayfun(@(i){fout{i}(2)},1:10)');
however, your loop is more efficient, faster, and easier to read.

4 件のコメント

Ronald CC
Ronald CC 2020 年 9 月 11 日
Thank you for your reply. I simplfied my original questions a lot. I wondered how to use arrayfun to replace the second for loop.
Adam Danz
Adam Danz 2020 年 9 月 11 日
I've updated my answer to address your question above.
Ronald CC
Ronald CC 2020 年 9 月 11 日
thanks
Adam Danz
Adam Danz 2020 年 9 月 14 日
Glad I could help.

この質問は閉じられています。

質問済み:

2020 年 9 月 10 日

閉鎖済み:

2021 年 8 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by