The str2double function is taking too long?
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
cui,xingxing
le 10 Juin 2021
Commenté : Walter Roberson
le 10 Juin 2021
The built-in function "str2double" is very time consuming when I want to convert an array of string type to an array of numertic type, especially when I have an array of string type with many elements(46259*503 size). Is there any way to improve the performance?
my os: win10
matlab 2021a
当我准备把一个string类型的数组(46259*503 大小)转换为numertic类型数组时候,此内置函数“str2double”非常耗时,特别是我的string类型数组较多元素的时候。请问有什么办法可以提高性能?
4 commentaires
Walter Roberson
le 10 Juin 2021
T3 = readmatrix('_040825_1735_IS.log', 'delimiter',' ');
That gives 46264 rows, 502 variables, everything already numeric.
Réponse acceptée
Walter Roberson
le 10 Juin 2021
There have been some test results posted showing that double() of a string() object is even faster than str2double()
format long g
S = compose("%.16g", randn(1000,50));
S(1:3,1:3)
time_for_double = timeit(@()double(S), 0)
time_for_str2double = timeit(@()str2double(S), 0)
time_for_sscanf = timeit(@()arrayfun(@(V)sscanf(V, '%f'),S))
t1 = tic;
arrayfun(@str2double,S);
time_for_str2double = toc(t1)
4 commentaires
Walter Roberson
le 10 Juin 2021
format long g
S = compose("%.16g", randn(1000,50));
S(1:3,1:3)
t = tic;
double(S);
time_for_double = toc(t)
t0 = tic;
str2double(S);
time_for_str2double = toc(t0)
t1 = tic;
arrayfun(@(V) sscanf(V, '%f'),S);
time_for_sscanf = toc(t1)
t2 = tic;
arrayfun(@(V) 1, S);
time_for_arrayfun = toc(t2)
t3 = tic;
arrayfun(@str2double,S);
time_for_str2double = toc(t3)
t4 = tic;
sscanf(sprintf(' %s',S.'), '%f', [size(S,2),Inf]).';
time_for_stephen_sscanf = toc(t4)
t5 = tic;
reshape(str2num(strjoin(S)),size(S));
time_for_str2num = toc(t5)
The last of those is marginally better than your sscanf/sprintf approach... on this run.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Data Type Conversion dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!