How to convert string to number and process underscores? (e.g. '57_77_' to 57.77)

조회 수: 10(최근 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:
  1. delete final '_'
  2. convert '_' to decimal point '.'
  3. 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
Daniel Bridges
Daniel Bridges 2018년 3월 15일
The goal is to read the table variable names in each file: Their order, number, and name differ. So I was thinking I needed to call it each time since the variable names generally differ each time.
Isn't there a better command than detectImportOptions since .VariableNames is all I need?

댓글을 달려면 로그인하십시오.

추가 답변(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:
and then delete the last character by
Other way would be doing this by using regexp:
a(idx)=['.',' ']
  댓글 수: 2

댓글을 달려면 로그인하십시오.

Jos (10584)
Jos (10584) 2018년 3월 14일
all in one go:
a = '12_23_'
v = str2num(strrep(a(1:end-1), '_', '.'))
  댓글 수: 2
Jos (10584)
Jos (10584) 2018년 3월 14일
haha, actually it is even three if you take indexing into account.

댓글을 달려면 로그인하십시오.

Daniel Bridges
Daniel Bridges 2018년 3월 14일
편집: Daniel Bridges 2018년 3월 14일
Here is one method that works, but I am not happy using a cell wrapper just to use Walter Roberson's cellfun; I'm sure there's a better way ...
volume = '57_77_';
volume = cellfun(@(S) S(1:end-1), {volume}, 'Uniform', 0);
volume = volume{1};
volume = regexprep(volume,'_','.');
volume = str2num(volume)
volume =
  댓글 수: 4
Daniel Bridges
Daniel Bridges 2018년 3월 14일
편집: Daniel Bridges 2018년 3월 14일
Oh! Sorry for my awkward question -- I accidentally combined Japanese and English grammar. (or else made a Japanese-type English grammar mistake) I will edit my question to clarify, too, if not simply for the sake of English.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by