Convert numeric 2D array to array of orders of values

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.)

 Accepted Answer

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 Comments

Many thanks. I was trying to avoid the loop approach, but you've done it much better than I would have.
You are welcome!
My initial thought was to look for a vectorized solution as well, but I couldn't come up with one.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2022b

Tags

Community Treasure Hunt

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

Start Hunting!