I have 6.4 sec recording of a discrete signal on 40Hz frequency (256 values).
How can I compute the variance of the signal? Please, share an algorithm in pseudo-code or in an actual programming language.
You want the sample variance:
$$ s^2 = \frac{1}{N-1} \sum_{n=0}^{N-1} (x_n - \mu_x)^2 $$
where the mean, $\mu_x$, is given by
$$ \mu_x = \frac{1}{N} \sum_{n=0}^{N-1} x_n. $$
The $\frac{1}{N-1}$ factor should be used to account for the bias that is otherwise there if $\frac{1}{N}$ is used. One way to think about this is the sample variance is computed from $N-1$ differences between samples, rather than $N$ samples.
The Sample Variance $s^2$ of a signal $\mathbf{y}$ with sample average $\mu$ may be computed as: $$ \begin{align*} s^2 &= \frac{1}{N-1} \sum_{i=1}^N (y_i - \mu)^2 \\ &= \frac{1}{N-1} \sum_{i=1}^N \left( \mu^2 - 2 \mu y_i + y_i^2 \right) \\ &= \frac{1}{N-1} \left[ N \mu^2 - 2 \mu \sum_{i=1}^N y_i + \sum_{i=1}^N y_i^2 \right] \\ &= \frac{1}{N-1} \left[ N \left(\frac{1}{N} \sum_{i=1}^N y_i \right)^2 - 2 \left(\frac{1}{N} \sum_{i=1}^N y_i \right) \sum_{i=1}^N y_i + \sum_{i=1}^N y_i^2 \right] &\left( \mu = \frac{1}{N} \sum_{i=1}^N y_i \right) \\ &= \frac{1}{N-1} \left[ N \left(\frac{1}{N} \sum_{i=1}^N y_i \right)^2 - 2 N \left(\frac{1}{N} \sum_{i=1}^N y_i \right)^2 + \sum_{i=1}^N y_i^2 \right] \\ &= \frac{1}{N-1} \left[ -N \left(\frac{1}{N} \sum_{i=1}^N y_i \right)^2 + \sum_{i=1}^N y_i^2 \right] \\ &= \frac{1}{N-1} \left[ -\frac{1}{N} \left(\sum_{i=1}^N y_i \right)^2 + \sum_{i=1}^N y_i^2 \right] \end{align*} $$
Below is an example in C++ code that implements the above equation. It may not be completely optimized, but it should be fairly efficient:
double sample_variance(double *signal, unsigned int signal_length) { double sum = 0.0; double sum2 = 0.0; for (unsigned int i=0; i<signal_length; i++) { sum += signal[i]; sum2 += signal[i]*signal[i]; } double N = (double)signal_length; return (sum2 - sum*sum/N)/(N-1.0); } Here is an article on what is Variance and how to calculate it. If you are using Matlab then you can form a column matrix consisting of the 256 values and send it to the var function in Matlab.