pub fn random_correlation<F>(n: usize, seed: Option<u64>) -> Array2<F>
Expand description
Generate a random correlation matrix
A correlation matrix is symmetric positive semi-definite with ones on the diagonal. These matrices are commonly used in statistics, finance, and machine learning.
The method generates a random matrix, computes A^T * A, and then normalizes the result to have ones on the diagonal.
§Arguments
n
- Dimension of the square correlation matrixseed
- Optional seed for the random number generator
§Returns
An nxn correlation matrix
§Examples
use scirs2_linalg::random::random_correlation;
// Generate a 4x4 random correlation matrix
let c = random_correlation::<f64>(4, None);
assert_eq!(c.shape(), &[4, 4]);
// Check that diagonal elements are 1
for i in 0..4 {
assert!((c[[i, i]] - 1.0).abs() < 1e-10);
}
// Check that off-diagonal elements are in [-1, 1]
for i in 0..4 {
for j in (i+1)..4 {
assert!(c[[i, j]] >= -1.0 && c[[i, j]] <= 1.0);
// Also verify symmetry
assert!((c[[i, j]] - c[[j, i]]).abs() < 1e-10);
}
}