Sorting elements of a matrix ignoring NaN

4 次查看(过去 30 天)
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!

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2016-3-21
编辑:Azzi Abdelmalek 2016-3-21
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 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by