MATLAB: Sorting elements of a matrix ignoring NaN

matrix manipulationsort

Dear All,
I have the following 4×4 matrix have containing numbers and NaN:
have = [5 NaN 4 9;
4 0 NaN 9;
-6 NaN 2 3;
1 7 NaN -3]
I would like to assign a rank (ascending/descending) to the elements of each colum of the matrix have. In the sorting procedure, the NaNs should be ignored and elements with the same value (column 4) should have the same (tied) rank.That is, I would like to obtain the following matrices:
want_ascend = [4 NaN 2 3;
3 1 NaN 3;
1 NaN 1 2;
2 2 NaN 1]
want_descend = [1 NaN 1 1;
2 2 NaN 1;
4 NaN 2 2;
3 1 NaN 3]
My attempt involving the sort function does not successfully ignore the NaN (which are ranked too).
[~,attempt]=sort(have,1,'descend')
attempt =
1 1 2 1
2 3 4 2
4 4 1 3
3 2 3 4
Any help would be highly appreciated. Thanks!

Best Answer

have = [5 NaN 4 9;
4 0 NaN 9;
-6 NaN 2 3;
1 7 NaN -3]
idx=isnan(have)
[n,m]=size(have)
[have_ascend,have_descend]=deal(zeros(n,m))
for k=1:m
v=have(:,k)
[~,~,kk]=unique(v)
have_ascend(:,k)=kk;
end
have_ascend(idx)=nan
You can get have_descend from have_ascend
have_descend=bsxfun(@minus,max(have_ascend)+1,have_ascend)