Convert numeric 2D array to array of orders of values
1 view (last 30 days)
Show older comments
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.)
0 Comments
Accepted Answer
Dyuman Joshi
on 27 Jan 2023
Edited: Dyuman Joshi
on 31 Jan 2023
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
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])
(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
Dyuman Joshi
on 31 Jan 2023
You are welcome!
My initial thought was to look for a vectorized solution as well, but I couldn't come up with one.
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!