str2double --> double
Jan Studnicka
on 14 Aug 2025
Latest activity Reply by WANG Zi-Xiang
on 28 Nov 2025 at 0:26
Did you know that function double with string vector input significantly outperforms str2double with the same input:
x = rand(1,50000);
t = string(x);
tic; str2double(t); toc
tic; I1 = str2double(t); toc
tic; I2 = double(t); toc
isequal(I1,I2)
Recently I needed to parse numbers from text. I automatically tried to use str2double. However, profiling revealed that str2double was the main bottleneck in my code. Than I realized that there is a new note (since R2024a) in the documentation of str2double:
"Calling string and then double is recommended over str2double because it provides greater flexibility and allows vectorization. For additional information, see Alternative Functionality."
23 Comments
Time DescendingThanks so much for sharing. I always used sscanf, from a recommandation found here: https://stackoverflow.com/questions/8363132/why-is-str2double-so-slow-in-matlab-as-compared-to-a-mex-function
x = rand(1,50000);
t = string(x);
s1=str2double(t);
s2=double(t);
isequal(s1,s2)
s3 = reshape(sscanf(sprintf('%s#', t), '%g#'), size(t));
isequal(s1,s3)
timeit(@() str2double(t))
timeit(@() double(t))
timeit(@() reshape(sscanf(sprintf('%s#', t), '%g#'), size(t)))
ans =
0.1206
ans =
0.0015
ans =
0.0109
Cool! Thanks for sharing!
This is interesting @Jan Studnicka, thanks for posting. The double conversion method of string is a relatively new, highly optimised and multithreaded C++ built-in. str2double is a much older .m file and has some um......legacy behaviour! Hence all the notes about not using in the doc.
With that said, the performance gap between the two here is more than I'd like and so I've brought this to the attention of the relvant peple in development to see what can be done.
Nice tip! Thanks for sharing.
tic and toc is certainly easier to remember than the syntax for using timeit. If I were to use timeit, I'd probably have to look up the documentation every time.
In this case the difference is pretty small, but you shouldn't use tic toc for comparing functions. timeit considers things like the slower first use of a function and statistical variation.
x = rand(1,50000);
t = string(x);
s1=str2double(t);
s2=double(t);
isequal(s1,s2)
timeit(@() str2double(t))
timeit(@() double(t))
interesting...
Sign in to participate