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!

 채택된 답변

Walter Roberson
Walter Roberson 2020년 7월 22일

1 개 추천

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.

댓글 수: 3

Marco Sartori
Marco Sartori 2020년 7월 22일
That worked perfectly. Thank you very much for your help and promptness!
At the same time, what if i'm working with a matrix instead of the simple vector above?
the process would be something like this but i cannot procede by specifing A(validmask(i,:)) for A(i,:)
ranks = zeros(size(A));
for i = 1:t
validmask(i,:) = ~isnan(A(i,:));
?
?
end
Walter Roberson
Walter Roberson 2020년 7월 22일
The easiest way would probably be to work column by column.
I can think of a vectorized algorithm, but it involves some sub2ind() tricks that are less than clear to read. Sometimes it just isn't worth doing unless your arrays are large enough that performance gets really important but at the same time not so large that the extra memory needed for vectorization is not a factor.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

madhan ravi
madhan ravi 2020년 7월 22일

2 개 추천

[~, where] = sort(A);
Wanted = where .* ~isnan(A)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2020년 7월 22일

댓글:

2020년 7월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by