Stefano
Stefano

Reputation: 1485

How can I get all pairwise correlations of a list of 2d matrices in MATLAB?

EDIT: The question has been edited after accepting the answer, to make it (hopefully) clearer.

Given the 3d matrix M(m, n, k), how do I calculate the 2d correlation matrix M(k, k) whose (i, j) entry is corr(M(m, n, i), M(m, n, j)).

Layman's terms

For example, I have a 3d matrix M(20, 20, 100), and I need a 2d matrix M(100, 100) which is a correlation matrix of each pairwise combination of M(20, 20, i), where i = 100. Since M(100, 100) is a correlation matrix, each cell is a single correlation coefficient (r), and the matrix is symmetric:

     a     b     c    ...
a    1     r_ab  r_ac 
b    r_ba  1     r_bc
c    r_ca  r_cb  1
...

Matlab MWE

I tried combinations of loops, corrcoef, corr2, with no avail.

% 3d matrix
m = rand(20, 20, 100);

% wrong output
r = corrcoef(m(:, :));

Upvotes: 0

Views: 288

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

You only need to reshape m so that each matrix is linearized into a column. Then corrcoef gives the desired result:

r = corrcoef(reshape(m, [], size(m,3)));

Upvotes: 1

Related Questions