Sorting elements of a matrix ignoring NaN
1 view (last 30 days)
Show older comments
Dear All,
I have the following 4x4 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!
0 Comments
Accepted Answer
Azzi Abdelmalek
on 21 Mar 2016
Edited: Azzi Abdelmalek
on 21 Mar 2016
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)
0 Comments
More Answers (0)
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!