Mikhail
Mikhail

Reputation: 21799

Relabel a matrix, replacing all unique numbers with 1..N

I'm using MATLAB. I have a matrix with N elements filled with numbers [1; N], but there are only K unique number between them (K is much less than N). What is an efficient way to relabel the matrix so that it contains only numbers [1; K]? Equal numbers should become equal, and not equal should become not equal.

Example for N = 10, K = 4:

[1 4 8 9 4 1 8 9 4 1] -> [1 2 3 4 2 1 3 4 2 1]

Upvotes: 3

Views: 183

Answers (1)

Sam Roberts
Sam Roberts

Reputation: 24127

Use the third output argument of unique:

a=[1 4 8 9 4 1 8 9 4 1];
[~, ~, b] = unique(a)
b =
     1     2     3     4     2     1     3     4     2     1

Upvotes: 8

Related Questions