Convert numeric 2D array to array of orders of values

조회 수: 1 (최근 30일)
dormant
dormant 2023년 1월 25일
댓글: Dyuman Joshi 2023년 1월 31일
I have an array of numbers, like this:
positions =
14 25 65 20 16 15 17 16
14 26 46 0 12 0 14 5
0 0 46 13 11 11 11 17
14 25 49 11 15 17 10 11
0 0 19 15 16 20 11 13
18 4 48 20 12 12 12 24
How can I create a similar-sized array with the numbers changed to their order in each column, ie
orders =
1 2 6 4 5 3 6 4
1 3 2 NaN 2 NaN 5 1
NaN NaN 2 2 1 1 2 5
1 2 5 1 4 4 1 2
NaN NaN 1 3 5 5 2 3
4 1 4 4 2 2 4 6
This needs to cope with values that are equal, giving them both the same place and then skipping a place for the next value.
(The orders array above was created by hand, so might have errors.)

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 1월 27일
편집: Dyuman Joshi 2023년 1월 31일
I couldn't think of a vectorized solution (yet), so here is the for loop approach.
If and when I find a vectorized solution, I will update my solution.
pos = [14 25 65 20 16 15 17 16
14 26 46 0 12 0 14 5
0 0 46 13 11 11 11 17
14 25 49 11 15 17 10 11
0 0 19 15 16 20 11 13
18 4 48 20 12 12 12 24];
for idx=1:size(pos,2)
%for operating on non zeros values
non=pos(:,idx)~=0;
%indices of unique values with reference to the column
[~,~,c]=unique(pos(non,idx));
for i=2:max(c)
%counting repetitions of each indices, ct - count
ct=nnz(c==(i-1));
if ct>1
%modifying indices accordingly
c(c>i)=c(c>i)+1;
c(c==i)=ct+i-1;
end
end
pos(non,idx)=c;
end
%assign Nan to zeros
pos(pos==0)=NaN
pos = 6×8
1 2 6 4 5 3 6 4 1 4 2 NaN 2 NaN 5 1 NaN NaN 2 2 1 1 2 5 1 2 5 1 4 4 1 2 NaN NaN 1 3 5 5 2 3 4 1 4 4 2 2 4 6
Additionally -
Since unique() identifies each Nan as a different element, updating zeros to NaN before would not have been helpful in this approach
unique([1 -1 NaN 0 -1 -1 0 NaN])
ans = 1×5
-1 0 1 NaN NaN
(Ideally) You should use tolerance based method to check for any values in MATLAB, rather than direct equality.
y=0;
abs(y-0)<1e-1
  댓글 수: 2
dormant
dormant 2023년 1월 31일
Many thanks. I was trying to avoid the loop approach, but you've done it much better than I would have.
Dyuman Joshi
Dyuman Joshi 2023년 1월 31일
You are welcome!
My initial thought was to look for a vectorized solution as well, but I couldn't come up with one.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by