Is it possible to vectorize this simple recursive function in loop?
7 ビュー (過去 30 日間)
古いコメントを表示
I have the following simple example code that has a recursive function in a loop. Is it possible to vectorize (to speed it up) it.
y=5;
tic;
for i=0:20
y=sin(y);
end
toc;
0 件のコメント
採用された回答
Jan
2021 年 3 月 31 日
編集済み: Jan
2021 年 4 月 1 日
No, this cannot be vectorized.
The idea of vectorization is that the same function is applied to many arguments independently from each other. You can e.g. vectorize the calculation of the sine for the arguments 1:100.
In you case the input of each iteration depends on the result of the former one. This does not allow to call the function with different input at the same time, but a sequential processing is required.
2 件のコメント
その他の回答 (1 件)
Rik
2021 年 4 月 1 日
Vectorization should only be attempted if there are more direct functions. Otherwise, for loops in Matlab are surprisingly optimal.
% example where vectorization will actually help:
data=rand(10,1);
tic,s=0;for n=1:numel(data),s=s+data(n);end,toc, tic,s=sum(data);toc
In your case it is impossible to vectorize the code. However, for sufficiently large values of your loop count, this will converge to 0. In the plot below I show the trends in the range -1 to 1, as every other value will be in this range after the first iteration.
y=zeros(2000,20);
y(1,:)=linspace(-1,1,size(y,2));
for n=2:size(y,1)
y(n,:)=sin(y(n-1,:));
end
plot(y)
ylabel('initial value'),xlabel('value after n recursions')
The convergence is fairly slow, requiring approximatly 100x more iterations for every division by 10:
y=1;k=1;crit=10^-k;
for n=1:(3*10^6)
y=sin(y);
if y<crit
fprintf('after % 11d iterations, y=%.8f\n',n,y)
k=k+1;crit=10^-k;
end
end
%Code run in this interface must be shorter than 55 seconds, but when I run
%this on my local copy of Matlab for more iterations, I get this output:
% after 295 iterations, y=0.09985802
% after 29992 iterations, y=0.00999990
% after 2999989 iterations, y=0.00100000
% after 299999986 iterations, y=0.00010000
% after 29999999984 iterations, y=0.00001000
So it might be possible to approximate the value given a starting value and number of iterations.
How you could look for such an approximation is an interesting mathematical question, for which I have neither time nor skill to find an answer.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!