Is it possible to vectorize this simple recursive function in loop?

9 visualizzazioni (ultimi 30 giorni)
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;

Risposta accettata

Jan
Jan il 31 Mar 2021
Modificato: Jan il 1 Apr 2021
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.

Più risposte (1)

Rik
Rik il 1 Apr 2021
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
Elapsed time is 0.000930 seconds.
Elapsed time is 0.000199 seconds.
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
after 295 iterations, y=0.09985802 after 29992 iterations, y=0.00999990 after 2999989 iterations, y=0.00100000
%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.

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by