1

I currently have a cell array in MATLAB that contains a list of serial numbers. Serial numbers are basically strings without any particular structure - so that my cell array is something like:

serial_numbers = {'serial1'; 'serial1'; 's2'; 'serial31010'}

Given that each unique string within serial_numbers corresponds to a different item, I would like to assign an integer value to each of them... so I can change

serial_numbers = {'serial1'; 'serial1'; 's2'; 'serial31010'}

into

new_serial_numbers = [1;1;2;3]

Right now, I do this by using the unique and strcmp functions as follows

unique_serial_numbers = unique(serial_numbers);
new_serial_numbers = nan(size(serial_numbers));

for i = 1:length(unique_serial_numbers)
   new_serial_numbers(strcmp(serial_numbers,unique_serial_numbers(i))) = i;
end

Of course this is really slow for large I would like to convert each serial into an integer value. Is there a faster way to do this?

1
  • does your cell array contain only numbers or also letters? Commented Jun 11, 2013 at 23:05

1 Answer 1

7

You were on the right track. After defining:

serial_numbers = {'serial1'; 'serial1'; 's2'; 'serial31010'}

This seems to be simple:

[~,~,new_serial_numbers ] = unique(serial_numbers,'stable')

will give:

new_serial_numbers =   1   1   2   3

Don't know about the performance of the 'unique' function

Sign up to request clarification or add additional context in comments.

1 Comment

+1 I've done this a bunch in production code and can confirm the unique() performance is about as good as you can expect for this. You can also grab the first two outputs of unique and now you have a symbol table that you can use to encode newly encountered strings using ismember and some logic to expand the table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.