I appreciate people getting back to me. I think I now understand what is going on. When calculating a standard deviation, we find the summation of

*Sqr(y_i - y_av)* with

*i* in the range (1,length) (formula given

here ). It is only necessary to calculate the average value of

*y, y_av*, once .

In the original code that I posted, I assumed that on a given bar, once

*y_av *was calculated its value was then fixed for that bar (

*def av_y= Average(y,length);*). However it appears that it is calculated at least 'length-1' more times if it appears within the sum function. During the summation, each calculation uses the bar of interest (with closing value =

*y_i*) and then finds the average value over length bars up to that bar. I guess we could say that the

*y_av* turns into a moving average when included in the sum function (i.e its value is now not fixed)

I figured this out by writing a little piece of matlab code that produces both the

*inbuilt* standard deviation,

*std1*, value and the

*mystd*,

*std2*, value produced in my original post. I have copied this below

Code:

```
% sign indicates a comment
x=[238.47 ,236.61, 240.00, 239.6, 238.63, 235.15, 233.82, 235.95]; % Visa close prices
% 7/9 7/8 7/7 7/6 7/2 7/1 6/30 6/29 dates
llength=4;
av1=mean(x(1:llength)); %finds average over 'llength' values
sqrsum1=0; %initialize summation
sqrsum2=0; %initialize summation
for i=1:llength
av2=mean( x(i : i+(llength-1) )); %finds average over llength values commencing at current x value i.e moving average
sqrsum1=sqrsum1+(x(i)- av1)^2;
sqrsum2=sqrsum2+(x(i)- av2)^2;
end
std1 = sqrt((sqrsum1/llength)) % corresponds to inbuilt in my original post
std2 = sqrt((sqrsum2/llength)) % corresponds to mystd in my original post
```

At least I know now where the error was in my assumption that

def av_y= Average(y,length);

def mystd = Sqrt( Sum(Sqr(y-av_y),length)/length );

should produce the correct standard deviation. Any thoughts or comments are much appreciated