matrix_correlation

matrix_correlation#

class braintools.metric.matrix_correlation(x, y)#

Compute Pearson correlation of upper triangular elements of two matrices.

This function calculates the correlation coefficient between corresponding upper triangular elements of two matrices, excluding the diagonal. This is useful for comparing connectivity matrices or similarity matrices.

Parameters:
  • x (brainstate.typing.ArrayLike) – First matrix. Must be 2-dimensional.

  • y (brainstate.typing.ArrayLike) – Second matrix. Must have the same shape as x.

Returns:

Pearson correlation coefficient between the upper triangular elements of the two matrices (excluding diagonal).

Return type:

float

Raises:

ValueError – If input arrays are not 2-dimensional.

Examples

>>> import jax.numpy as jnp
>>> import braintools as braintools
>>> # Create two correlation matrices with similar structure
>>> x = jnp.array([[1.0, 0.8, 0.3], [0.8, 1.0, 0.5], [0.3, 0.5, 1.0]])
>>> y = jnp.array([[1.0, 0.7, 0.4], [0.7, 1.0, 0.6], [0.4, 0.6, 1.0]])
>>> corr = braintools.metric.matrix_correlation(x, y)
>>> print(f"Matrix correlation: {corr:.3f}")
>>>
>>> # Compare connectivity matrices from different conditions
>>> baseline_fc = jnp.random.rand(5, 5)
>>> baseline_fc = (baseline_fc + baseline_fc.T) / 2  # Make symmetric
>>> jnp.fill_diagonal(baseline_fc, 1.0)  # Set diagonal to 1
>>>
>>> treatment_fc = baseline_fc + 0.1 * jnp.random.rand(5, 5)
>>> similarity = braintools.metric.matrix_correlation(baseline_fc, treatment_fc)
>>> print(f"Condition similarity: {similarity:.3f}")

Notes

The function uses jnp.triu_indices_from(x, k=1) to extract upper triangular elements, where k=1 excludes the diagonal.

This measure is particularly useful for:

  • Comparing functional connectivity matrices across conditions

  • Assessing similarity of network structures

  • Validating model predictions against empirical connectivity

For matrices that are not symmetric, only the upper triangle is used, which may not capture the full relationship structure.

See also

functional_connectivity

Compute connectivity matrix from time series

weighted_correlation

Weighted correlation for individual vectors