How to read formated data with implied decimal point
1 次查看(过去 30 天)
显示 更早的评论
Hello,
Is there any option in textscan or sscanf to read numbers with implied decimal format?
For example, in fortran format f4.2 would read 1234 as 12.34
I know that I can do it in two steps with various ways, but is there any way to do it while reading the number?
Thank you Petros
0 个评论
回答(1 个)
Cedric
2013-4-16
编辑:Cedric
2013-4-16
Not to my knowledge, but even the conversion in multiple steps is interesting (and it will prop up your question as a small challenge if you are lucky, so you may end up having the answer that you want ;-))..
% Updated @4:50pm EDT.
n = 1e6 ;
s = repmat('1234 5678 9876 5432 1098 ', 1, n) ;
tic ;
s_tmp = s(s >= '0') ;
num_1 = 10.^(1:-1:-2) * reshape(s_tmp-'0', 4, []) ;
toc
tic ;
num_2 = sscanf(s, '%f') / 100 ;
toc ;
tic ;
num_3 = sscanf(s, '%4f') / 100 ;
toc ;
tic ;
num_4 = [1,1/100] * reshape(sscanf(s, '%2f'), 2, []) ;
toc ;
tic ;
num_5 = [10.^(1:-1:-2),0] * reshape(s-'0', 5, []) ;
toc
Output:
Elapsed time is 0.352726 seconds.
Elapsed time is 0.891862 seconds.
Elapsed time is 0.996174 seconds.
Elapsed time is 1.657756 seconds.
Elapsed time is 0.221108 seconds. <= winner so far.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Export 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!