How to convert string to number and process underscores? (e.g. '57_77_' to 57.77)
Mostra commenti meno recenti
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
1 Commento
Daniel Bridges
il 14 Mar 2018
Risposta accettata
Più risposte (3)
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 Commenti
Jos (10584)
il 14 Mar 2018
you can remove the last element of the string before the replacement of the underscore ...
Birdman
il 14 Mar 2018
Yes, it is up to user.
Jos (10584)
il 14 Mar 2018
all in one go:
a = '12_23_'
v = str2num(strrep(a(1:end-1), '_', '.'))
2 Commenti
Birdman
il 14 Mar 2018
You say all in one go but you use two functions in one line, actually it is all in two go :)
Jos (10584)
il 14 Mar 2018
haha, actually it is even three if you take indexing into account.
Daniel Bridges
il 14 Mar 2018
Modificato: Daniel Bridges
il 14 Mar 2018
4 Commenti
Birdman
il 14 Mar 2018
Check mine and Jos' answer.
Daniel Bridges
il 14 Mar 2018
Birdman
il 14 Mar 2018
That was a misunderstanding, I have just edited it. Sorry for the misunderstanding.
Daniel Bridges
il 14 Mar 2018
Modificato: Daniel Bridges
il 14 Mar 2018
Categorie
Scopri di più su Data Type Conversion in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!