Extract numbers from char type
Ältere Kommentare anzeigen
how can I extract the numbers from a character array value of '4.64 km' and return them as 4.64?
Akzeptierte Antwort
Weitere Antworten (2)
Or, in one line of code:
s = '4.64 km';
num = sscanf(s, '%f') % num will be a double
1 Kommentar
Walter Roberson
am 18 Okt. 2022
Yes this works well when the number is at the beginning. You can also put literal text into the format if you expect an exact match.
The suggestions to use regexp to extract the text of the number work well when you need flexibility.
In cases where you have tables of text see textscan() which can be used on a character vector that has embedded newlines.
a='4.65 km';
r=regexp(a,'\d*[.]*\d*','match');
str2num(r{1})
Kategorien
Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!