Extract numbers from char type
29 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Yoseph
am 18 Okt. 2022
Kommentiert: Star Strider
am 19 Okt. 2022
how can I extract the numbers from a character array value of '4.64 km' and return them as 4.64?
0 Kommentare
Akzeptierte Antwort
Star Strider
am 18 Okt. 2022
Bearbeitet: Star Strider
am 18 Okt. 2022
Probably the easiest way —
s = '4.64 km';
c = regexp(s, '\d*\.\d*|\d*', 'match')
n = str2double(c)
EDIT — (18 Oct 2022 at 19:38)
In the event any of the numbers are negative —
s = '4.64 -42 2 -3.14 km';
c = regexp(s, '(\-\d*|\d*)\.\d*|(\-\d*|\d*)', 'match')
n = str2double(c)
.
4 Kommentare
Star Strider
am 19 Okt. 2022
I saw that and wondered, however I did not change my answer, and just learned from the important parts of your syntax.
Weitere Antworten (2)
Les Beckham
am 18 Okt. 2022
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.
Siehe auch
Kategorien
Mehr zu Text Data Preparation finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!