Star
Star

Reputation: 2299

Renumber contiguous equal values in a matrix in Matlab

I have a matrix A in Matlab of dimension MxN with the following structure

A=[23  10 3;
   23  4  5;
   456 6  8;
   456 8  9;
   456 12 14;
   5   56 32]

The key characteristic of A is that in the first column there are some values repeated a certain (not fixed) number of times: in the example 23 is repeated twice, 456 is repeated 3 times, 3 is repeated once.

I would like some advice to write a piece of code replacing 23 with 1, 456 with 2, 5 with 3 so that I transform A into

A=[1 10 3;
   1 4  5;
   2 6  8;
   2 8  9;
   2 12 14;
   3 56 32]

This code does what I want but it contains a double loop that I would like to avoid

   C=unique(A(:,1),'stable');
   for j=1:size(C,1)
       for h=1:size(A,1)
           if A(h,1)==C(j)
               A(h,1)=j;
           end
       end
   end

Upvotes: 0

Views: 65

Answers (1)

Wolfie
Wolfie

Reputation: 30156

You can use unique as suggested by rahnema. From the docs we can get more insight:

[C,ia,ic] = unique(A) also returns index vectors ia and ic.
- If A is a matrix or array, then C = A(ia) and A(:) = C(ic).

Which means that ic, the third output, returns which row of the unique vector C corresponds to the given row of A. In particular, you will want to use the 'stable' argument to keep the same order, otherwise the indices will also be sorted with respect to the unique values.


So, in summary, assign the third output of unique to the first column of A.

[~, ~, A(:,1)] = unique(A(:,1), 'stable');

Output:

>> A =

 1    10     3
 1     4     5
 2     6     8
 2     8     9
 2    12    14
 3    56    32

Upvotes: 1

Related Questions