The str2double function is taking too long?
조회 수: 14 (최근 30일)
이전 댓글 표시
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
Walter Roberson
2021년 6월 10일
T3 = readmatrix('_040825_1735_IS.log', 'delimiter',' ');
That gives 46264 rows, 502 variables, everything already numeric.
채택된 답변
Walter Roberson
2021년 6월 10일
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
Walter Roberson
2021년 6월 10일
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.
추가 답변 (0개)
참고 항목
카테고리
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!