MATLAB: Ignore NaN values when sorting

nanrank

Good afternoon everybody!
I have a matrix of the type:
A = [10 NaN 20 NaN]
and I want to put a rank in ascending order to these values but, if there is a NaN value, it is ignored or set equal to 0.
For instance, the result can be:
rank = [1 0 2 0]
It would be awesome if you can help me with this enigma.
Thank you!

Best Answer

validmask = ~isnan(A);
[~, nonnanrank] = sort(A(validmask));
rank = zeros(size(A));
rank(validmask) = nonnanrank;
However I recommand that you use a different variable name rather than rank to avoid interfering with using the MATLAB function rank() . rank() is used less frequently than sum() or length() are, so this is perhaps less of an issue than using those variables would be.