Extract numbers from char type
조회 수: 37 (최근 30일)
이전 댓글 표시
how can I extract the numbers from a character array value of '4.64 km' and return them as 4.64?
댓글 수: 0
채택된 답변
Star Strider
2022년 10월 18일
편집: Star Strider
2022년 10월 18일
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
Star Strider
2022년 10월 19일
I saw that and wondered, however I did not change my answer, and just learned from the important parts of your syntax.
추가 답변 (2개)
Les Beckham
2022년 10월 18일
Or, in one line of code:
s = '4.64 km';
num = sscanf(s, '%f') % num will be a double
댓글 수: 1
Walter Roberson
2022년 10월 18일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!