Reputation: 29
I have the following code, how will I be able to simplify it using the function as it currently runs pretty slow, assume X
is 10x7 and Y
is 4x7 and D
is a matrix stores the correlation between each pair of vectors. If the solution is to use the xcorr2
function can someone show me how it is done?
for i = 1:4
for j = 1:10
D(j,i) = corr2(X(j,:),Y(i,:));
end
end
Upvotes: 3
Views: 2704
Reputation: 8467
With corrcoef
you can do this without a loop, and without using a toolbox:
D = corrcoef([X', Y']);
D = D(1 : size(X, 1), end - size(Y, 1) + 1 : end);
A drawback is that more coefficients are computed than necessary.
The transpose is necessary because your matrices do not follow the Matlab convention to enumerate samples with the first index and variables with the second.
Upvotes: 0
Reputation: 112659
Use pdist2
(Statistics toolbox) with 'correlation'
option. It's faster than your code (even with preallocation), and requires just one line:
D = 1-pdist2(X,Y,'correlation');
Upvotes: 5
Reputation: 21563
Here is how I would do it:
First of all, store/process your matrix transposed. This makes for easier use of the correlation function.
Now assuming you have matrices X
and Y
and want to get the correlations between combinations of columns, this is easily achieved with a single loop:
X
corrcoef
to determine the correlation with all columns of Y
at once.X
Alternate to this, you can check whether it helps to replace corr2
in your original code with corr
, xcorr
or corrcoef
and see which one runs fastest.
Upvotes: 0