Is it possible to vectorize this simple recursive function in loop?
조회 수: 9 (최근 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!