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 Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by