Is it possible to vectorize this simple recursive function in loop?
Mostrar comentarios más antiguos
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;
Respuesta aceptada
Más respuestas (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.
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
