MATLAB: How to ignore NaN values in the CORR Function?

My problem in MATLAB is the opposite of the other problems reported here between NAN values in CORR function.

If I have a matrix A = [1;2;3;4] and a matrix B = [3;5;7;8], the correlation corr(A,B) is 0.9898.Ok for that.

But, If there is a NaN value in B, such as: B = [3;5;7;NaN], the correlation corr(A,B) will be NaN instead of 1.0000 (that is the correlation of the not NaN values of A (1;2;3) and B(3;5;7).

What can I do to make it calculate the corr function ignoring this NaN values making it give me answers different of "NaN"?

Upvotes: 0

Views: 2702

Answers (2)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

You can call the corr function with the rows parameter set to complete. From the official documentation:

'complete' uses only rows with no missing values

For example:

A = [1;2;3;4];
B = [3;5;7;NaN];
r = corr(A,B,'rows','complete')

Output:

r =
     1.0000

Upvotes: 1

Cris Luengo
Cris Luengo

Reputation: 60494

Many statistics functions have variants that ignore NaN values, I don't know if corr does too. But you can always fake it:

indx = ~(isnan(A) | isnan(B));
corr(A(indx),B(indx));

Upvotes: 1

Related Questions