How to replace elements in an array with the indices of the array's sorted, unique values?
41 views (last 30 days)
This is what I have (below). I am wondering if there is a better way of accomplishing the aforementioned task. Also, is there a name for this process? I don't have a formal computer science education so I'm curious.
A = randi(9,5,2); % Initialize matrix.
uA = unique(A); % Unique values of A.
B = A; % Output.
for idx = 1:length(uA) % Index to unique values, replace with
B(B == uA(idx)) = idx; % their sorted indices.
More Answers (2)
Walter Roberson on 23 Oct 2017
That code is wrong: you are changing B "in place" and comparing against all of it, so you could end up changing the same location multiple times. For example, suppose one of the unique values was 1/2 and another was 1, and those got index values 1 and 2 respectively. You change the 1/2 entries to 1. But that creates a 1 that is then there to be matched against uA(2) so you would mistake the 1 that was the index with the 1 that was the value.
You should just use
[uA, B] = unique(A);