MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today**New to MATLAB?**

Asked by Mark
on 18 Jun 2013

I have a matrix of values that include integers >= 0. There are repeats, and also gaps in consecutiveness. I would like to collapse the data into consecutive integers, keeping the order intact.

Example: [ 0 1 4 4 1 5 8 1 4]

would go to

[ 0 1 2 2 1 3 4 1 2]

I can do this with loops and brute force, but I'm wondering if there's any quick way to do this since it is frequently called within a loop?

Thanks!

*No products are associated with this question.*

Answer by Tom
on 18 Jun 2013

Accepted answer

[~,~,I] = unique([ 0 1 4 4 1 5 8 1 4]); disp(I-1)

## 3 Comments

## John (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/79414#comment_155589

I don't understand what you're aiming for... the example result you show isn't consecutive (1 to 3? 4 to 1?), and you're entirely changing some of the numbers.

## John (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/79414#comment_155590

It looks like you just divided everything by 2, rounding up.

## Mark (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/79414#comment_155642

Not consecutive in the array, but consecutive in the counting of unique numbers in the original. I.e., there are 5 unique numbers in the original vector, 0 1 4 5 and 8. I wanted to map those to 0 1 2 3 4. (The divide by two and round was just coincidence!) The problem has been solved below. Thanks.