function pval = ljungbox(xV,pmax)
% pval = ljungbox(xV,pmax)
% LJUNGBOX performs the Ljung-Box and computes the p-value for this test.
% INPUT
% - xV      : the vector of the time series.
% - pmax    : the largest order to compute autocorrelation for.
% OUTPUT
% - pval       : the p-value for the Ljung-Box test.

n = length(xV);
autM = autocor(xV,1,pmax);
autV = autM(2:pmax+1,2);
Q = n*(n+2)*sum(autV.^2 ./ (n-[1:pmax]'));
pval = 1-chi2cdf(Q,pmax);
