How to convert string to number and process underscores? (e.g. '57_77_' to 57.77)
9 ビュー (過去 30 日間)
古いコメントを表示
How do you convert a string with underscores to a number, namely '57_77_' to 57.77? What commands would you use?
I am looking through the documentation, e.g. join, compose, sprintf, extractBefore, trying to figure out how to process such a string, namely to execute the steps:
- delete final '_'
- convert '_' to decimal point '.'
- convert string to number
採用された回答
Stephen23
2018 年 3 月 14 日
編集済み: Stephen23
2018 年 3 月 14 日
Faster and more efficient than using str2num (which hides a slow eval call inside) is to simply use the low-level function sscanf:
>> sscanf(strrep('57_77_','_','.'),'%f')
ans = 57.770
This is ten times faster than the accepted answer (1e4 iterations):
Elapsed time is 0.277028 seconds. % my code
Elapsed time is 2.63426 seconds. % accepted answer
5 件のコメント
Stephen23
2018 年 3 月 14 日
If the CSV files all have the exactly same format then there is no reason why detectImportOptions has to be called 40 times. Why not move it out of the function, call it once before the loop, and pass that data as an input argument?
その他の回答 (3 件)
Birdman
2018 年 3 月 14 日
編集済み: Birdman
2018 年 3 月 14 日
The wise thing would be to first convert underlines to dots by using regexprep or strrep:
a=regexprep(a,'_','.')
or
a=strrep(a,'_','.')
and then delete the last character by
a(end)=[]
a=str2num(a)
Other way would be doing this by using regexp:
idx=regexp(a,'_')
a(idx)=['.',' ']
a=str2num(a)
2 件のコメント
Jos (10584)
2018 年 3 月 14 日
you can remove the last element of the string before the replacement of the underscore ...
Jos (10584)
2018 年 3 月 14 日
all in one go:
a = '12_23_'
v = str2num(strrep(a(1:end-1), '_', '.'))
2 件のコメント
Birdman
2018 年 3 月 14 日
You say all in one go but you use two functions in one line, actually it is all in two go :)
Daniel Bridges
2018 年 3 月 14 日
編集済み: Daniel Bridges
2018 年 3 月 14 日
4 件のコメント
Birdman
2018 年 3 月 14 日
That was a misunderstanding, I have just edited it. Sorry for the misunderstanding.
参考
カテゴリ
Help Center および File Exchange で String についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!