How to replace elements in an array with the indices of the array's sorted, unique values?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Dominik Mattioli
am 23 Okt. 2017
Kommentiert: Stephen23
am 23 Okt. 2017
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.
end
0 Kommentare
Akzeptierte Antwort
Stephen23
am 23 Okt. 2017
Bearbeitet: Stephen23
am 23 Okt. 2017
All you need is the third output of unique followed by reshape:
>> [~,~,Y] = unique(A);
>> reshape(Y,size(A))
For example:
>> B % from running your code
B =
4 5
2 3
1 4
4 7
5 6
>> [~,~,Y] = unique(A);
>> reshape(Y,size(A))
ans =
4 5
2 3
1 4
4 7
5 6
2 Kommentare
Stephen23
am 23 Okt. 2017
@Dominik Mattioli: I hope that it helps!
It is always worth reading the documentation for every function that you use: there is a lot of useful info in there!
Weitere Antworten (2)
Walter Roberson
am 23 Okt. 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);
Steven Lord
am 23 Okt. 2017
Do you want the ic third output from unique, or a version of that output that you've used reshape on to make it the same shape as A?
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!