use corr on different length matrix in matlab

To calculate the correlation between two matrices of different lengths, you can use the built-in corr function in Matlab. However, the matrices must have the same number of columns, and to do so, you may need to add NaN values to the shorter matrix to make it the same length as the longer matrix. Here's an example code snippet demonstrating how to do this:

main.m
% Example matrices of different lengths
A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
B = [10, 11, 12, 13; 14, 15, 16, 17];

% Pad the shorter matrix with NaN values
if size(A,1) < size(B,1)
    A = [A; nan(size(B,1)-size(A,1), size(A,2))];
else
    B = [B; nan(size(A,1)-size(B,1), size(B,2))];
end

% Calculate the correlation between the two matrices
R = corr(A, B);
357 chars
14 lines

This code first checks which matrix is shorter, and then adds NaN values to the end of that matrix in order to make it the same length as the longer matrix. The corr function is then used to calculate the correlation between the two matrices, taking into account any NaN values that were added.

Note that when using corr on matrices with missing data (represented by NaN values), the function treats these as missing observations and calculates the correlation using only the non-missing values pairwise between the two matrices.

gistlibby LogSnag