How to speed up code for converting an array of strings to array of numbers
3 次查看(过去 30 天)
显示 更早的评论
I have a cell containing a large vector (over 1.5M entries ) of strings. Many entries are common, so that there are about 15k unique entries in this vector. I need to convert the array of strings to an array of numbers, where there is one-to-one correspondence between each string and the corresponding number. Each string contains 32 characters. I am using the following code that is taking over half hour to run. I suspect that the for-loop is the culprit. I would really appreciate it if anyone can suggest a faster way of accomplishing the same, since I have to process many datasets?
Thanks for your help.
data_raw = textscan(fid,'%s %f %f %f %f %s %s %s %s %s','Delimiter',',');
%data_raw = textscan(fid,'%f %f %f %f %f %s %s %s %s %s %s','Delimiter',',');
% following code converts alpha TTIDs to numeric TTIDs
unique_TTIDs_alpha = string(unique(data_raw{1}));
n_points = length(data_raw{1,1});
n_points_unique = length(unique_TTIDs_alpha);
TTIDs_numeric = zeros(n_points,1);
tic
for ii = 1: n_points_unique
idx = find(data_raw{1} == unique_TTIDs_alpha(ii));
TTIDs_numeric(idx,1) = ii;
end
0 个评论
采纳的回答
Star Strider
2018-4-6
I have no idea what your final goal is.
Note that the unique function has as as many as 3 outputs. The first are the unique elements, the second are the indices of the first occurrence of each unique element, and the third are indices (corresponding to the first 2 outputs) of each element, so that replicated elements all get the same number. See the documentation on the unique function for a full discussion.
0 个评论
更多回答(2 个)
Brendan Hamm
2018-4-6
I am not sure how much of a speedup to expect in the conversion, but I would highly consider using categorical variables for this. This can actually be done directly in textscan using the %C format identifier. In most cases I think this will solve your problem.
If the purpose of the conversion is to have a variable which is easier to query (i.e. numeric comparisson), the categorical will likely do what you are looking for. Take a look at the doc and the methods for this class:
doc categorical
methods('categorical')
If you actually need a numeric value then it is worth noting that a categorical is storing the data in a numeric (uint*, where * depends on the number of categories) format behind the scenes, so can easily be converted to numeric using one of the conversion functions (double, single, uint16). With 15,000 unique categories, you could not represent this with a uint8.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!