[Scilab-users] vector operation replacing for loop

Samuel Gougeon sgougeon at free.fr
Thu Nov 1 13:40:55 CET 2018


Hello,

Le 01/11/2018 à 09:27, Heinz Nabielek a écrit :
> Sorry, Scilab friends, I am still not fluid with vector operations.
> Can someone rewrite the for loop for me into something much more efficient?
>
> n=1000;
> Z=grand(1,n,'nor',0,1);
> r=0.9;
> V=Z;
> for i=2:n;
> 	V(i)=r*V(i-1)+sqrt(1-r^2)*Z(i);
> end;
>
> The transformation generates an autocorrelated (here rho=0.9) normal distribution V from an uncorrelated normal distribution Z and eventually I will need it for very much larger n values....

You may use filter(), with a feedback component (since V(i) depends on 
the previous state V(i-1) computed at the previous step).
However, as shown below, a quick trial shows an initial discrepancy 
between filter() result and yours with the explicit loop.
I don't know why. May be the setting for the initial condition should be 
carefully considered/tuned...

n=1000;
Z=grand(1,n,'nor',0,1);
r=0.9;
V=Z;
for  i=2:n;
     V(i)=r*V(i-1)+sqrt(1-r^2)*Z(i);
end;

y  =  filter(sqrt(1-r^2),[1  -r],  Z);

clf
subplot(3,1,1),  plot(Z),  ylabel('input Z')
subplot(3,1,2),  plot(V),  ylabel('V')
d  =  abs(y-V);  d(d==0)  =  %nan;
subplot(3,1,3),  plot2d("nl",d),  title('filter() - V')
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.scilab.org/pipermail/users/attachments/20181101/21bf886d/attachment.htm>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: dhmcbnifdbmlkjck.png
Type: image/png
Size: 16996 bytes
Desc: not available
URL: <https://lists.scilab.org/pipermail/users/attachments/20181101/21bf886d/attachment.png>


More information about the users mailing list