Compute the correlation matrix associated with a covariance matrix
This functionality does not run in MATLAB.
stats::correlationMatrix(cov) returns to correlation matrix cor of the variance-covariance matrix cov. It is given by:
A covariance matrix C should be positive (semi-)definite and hence satisfies |Cij|2 ≤ Cii Cjj for all indices i, j. Consequently, the absolute values of the entries of the corresponding correlation matrix do not exceed 1.
With the option CovarianceMatrix, the routine stats::reg returns the variance-covariance matrix of the fit parameters in a regression analysis. The corresponding correlation matrix of the fit parameters is computed conveniently by applying stats::correlationMatrix to this matrix. Cf. Example 2.
We generate a positive definite matrix that may serve as a covariance matrix:
A := matrix([[4, -3, 2], [-1, 2, 1], [0, 1, 1]]): cov := A*linalg::transpose(A)
The corresponding correlation matrix is:
If the input matrix consists of floating-point data, the result is a matrix of floats:
delete A, cov:
We consider a covariance matrix arising in a non-linear regression problem. The model function y = a + b cos(x - c) is to be fit to the following randomized data:
r := stats::uniformRandom(-0.1, 0.1): xdata := [i $i = 1..100]: ydata := [1 + 2*cos(x - 3) + r() $ x in xdata]:
By construction, the variance of the y values is the variance of the uniformly distributed random data on the interval [- 0.1, 0.1] generated by the random generator r. This variance is . We use stats::reg to obtain estimates of the fit parameters a, b, c of the model. Appropriate weights for the regression are given by . The option CovarianceMatrix makes stats::reg include the covariance matrix cov of the fit parameters in its return list:
weights := [300 $ i = 1..100]: DIGITS:= 4: [abc, chisquare, cov] := stats::reg(xdata, ydata, weights, a + b*cos(x - c), [x], [a, b, c], StartingValues = [1, 2, 3], CovarianceMatrix)
The correlation matrix of the parameters a, b, c is obtained via stats::correlationMatrix applied to the covariance matrix cov returned by stats::reg:
delete r, xdata, ydata, weights, DIGITS, abc, chisquare, cov:
Matrix of the same dimension and type as the input matrix cov. FAIL is returned if at least one of the diagonal elements of the input matrix cov is zero.