MATLAB: How to compute sum of a series using Symbolic Math Toolbox 5.4 (R2010a)

deviationmeanstandardSymbolic Math Toolbox

I want to create a vector, X of symbolic variables of length, n. Now, I wish to compute the variance of the symbolic vector which is essentially expressed as a sum of a series.

Best Answer

The following code may be used in MATLAB to create and compute the variance of a symbolic vector:
% Compute variance symbolically for a vector of length n
syms n i
Xi = sym('X[i]');
mean = symsum(Xi,i,1,n)/n;
variance = symsum((Xi-mean)^2,i,1,n)
% Compute variance for n = 3
N = 3;
variance = subs(variance,n,N)
% Substitute values for the vector X
X = arrayfun( @(x) sprintf( 'X[%d]', x ), 1:N, 'UniformOutput', false ); % Cell array of vector, X
variance = double(subs(variance,X,num2cell(rand(1,N)))) % Substitute numbers in cell array for all the elements of X
You may use _PLUS or SUM in the Notebook interface of the Symbolic Math Toolbox to compute the variance of a symbolic vector of length, n, for example:
mean:= sum(X[i], i=1..n)/n;
variance:= sum((X[i] - mean)^2, i=1..n);
Please see the attached notebook for a more detailed example.
Related Question