How to make str2double recognize comma delimited numbers?
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
KD
el 19 de Mzo. de 2025
Respondida: Stephen23
el 19 de Mzo. de 2025
I'm reading in an excel file and I have a column that I need to convert all the values from string to text.
Currently Im using:
data.col1 = str2double(data.col1);
and this is merging the values in my column.
For example, it goes from '2,3' to 23. Is there a way I can do this, but make it so it recognizes it is 2 separate numbers 2 and 3?
Thanks!
2 comentarios
Respuesta aceptada
Star Strider
el 19 de Mzo. de 2025
Editada: Star Strider
el 19 de Mzo. de 2025
It depends on what the actual numbers are. You can likely simplify this to use only '\d*' if they are only integers.
One approach —
data.col1 = {'2,3';'42';'1.23';'4.56,7.89';'21,3.14';'2.718,99'};
data.col1 = regexp(data.col1, '\d*\.\d*|\d*', 'match')
data.col1 = cellfun(@str2double,data.col1, Unif=0)
data.col1
EDIT — (19 Mar 2025 at 17:46)
Added rows to ‘data.col1’ to illustrate its results. It would be helpful to know more about whatt it actually is.
.
4 comentarios
Walter Roberson
el 19 de Mzo. de 2025
col1 = {'123', '123.', '.123', '.', '', 'abc'}
regexprep(col1, '(\d*\.\d*|\d*)', '|$1|')
We can see from this test that '\d*\.\d*|\d*' matches a bare . by itself, but does not (without further options) match the empty string.
To get it right you need to use a more complicated pattern, such as
regexprep(col1, '(\d+(\.\d*)?|\.\d+)', '|$1|')
Star Strider
el 19 de Mzo. de 2025
@Walter Roberson — I’d not considered the isolated decimal point, although it certainly could be a possibility. Thank you yet again.
As it turns out, apparently they’re all integers, so here strsplit may be all that’s necessary.
Más respuestas (2)
Stephen23
el 19 de Mzo. de 2025
Using SSCANF will likely be more efficient than relying on regular expressions:
T = readtable('ExampleExcel.xlsx')
F = @(t)sscanf(t,'%f,',[1,Inf]);
T.RC = cellfun(F, T.RC, 'uni',0)
0 comentarios
Mike Croucher
el 19 de Mzo. de 2025
Editada: Mike Croucher
el 19 de Mzo. de 2025
Try using str2num instead
str2num('2,3',Evaluation = "restricted")
or possibly this
s = '2,3';
str2double(split(s, ','))
Ver también
Categorías
Más información sobre Spreadsheets en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!