Berk U.
Berk U.

Reputation: 7188

Efficient Way to Replace Custom Strings with Numbers in MATLAB

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?

Upvotes: 1

Views: 1872

Answers (1)

Hoogendijk
Hoogendijk

Reputation: 100

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

Upvotes: 7

Related Questions