Extract numbers from char type

38 visualizaciones (últimos 30 días)
Yoseph
Yoseph el 18 de Oct. de 2022
Comentada: Star Strider el 19 de Oct. de 2022
how can I extract the numbers from a character array value of '4.64 km' and return them as 4.64?

Respuesta aceptada

Star Strider
Star Strider el 18 de Oct. de 2022
Editada: Star Strider el 18 de Oct. de 2022
Probably the easiest way —
s = '4.64 km';
c = regexp(s, '\d*\.\d*|\d*', 'match')
c = 1×1 cell array
{'4.64'}
n = str2double(c)
n = 4.6400
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')
c = 1×4 cell array
{'4.64'} {'-42'} {'2'} {'-3.14'}
n = str2double(c)
n = 1×4
4.6400 -42.0000 2.0000 -3.1400
.
  4 comentarios
Walter Roberson
Walter Roberson el 19 de Oct. de 2022
darn I forgot the case of no period
Star Strider
Star Strider el 19 de Oct. de 2022
I saw that and wondered, however I did not change my answer, and just learned from the important parts of your syntax.

Iniciar sesión para comentar.

Más respuestas (2)

Les Beckham
Les Beckham el 18 de Oct. de 2022
Or, in one line of code:
s = '4.64 km';
num = sscanf(s, '%f') % num will be a double
num = 4.6400
  1 comentario
Walter Roberson
Walter Roberson el 18 de Oct. de 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.

Iniciar sesión para comentar.


David Hill
David Hill el 18 de Oct. de 2022
a='4.65 km';
r=regexp(a,'\d*[.]*\d*','match');
str2num(r{1})
ans = 4.6500

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by