How to converting string values in a cell array to numbers when some strings are non-numeric (e.g. 'null')
55 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Kevin Johnson
el 16 de Mzo. de 2021
Comentada: Kevin Johnson
el 17 de Mzo. de 2021
I have a cell array like this: T =
{'0.115513'}
{'0.113281'}
{'0.112723'}
{'null' }
{'0.110491'}
{'0.107701'}
I want to convert it to an array of numbers, so I search for 'null' and replace it with zero before using cell2mat(T). So far so good, that works.
The problem is that the actual vector T in my problem is many thousands of cells long, and somehwere apparently there are other non-numeric strings that are not 'null', because searching and replacing 'null' still results in a failure of the cell2mat conversion.
"Error using cat
Dimensions of arrays being concatenated are not consistent.
Error in cell2mat (line 83) m{n} = cat(1,c{:,n});"
Without using a loop of some kind, how can I convert all the legitimately numeric strings to numbers, while replacing the non-numeric strings with zero, or better, with NaN? If I knew what these non-numeric strings were ahead of time it would be simple, but I do not know that.
Thanks
2 comentarios
Stephen23
el 17 de Mzo. de 2021
"...so I search for 'null' and replace it with zero before using cell2mat(T) ... how can I convert all the legitimately numeric strings to numbers..."
Note that your current code does not convert any string data to numeric, because cell2mat does not convert any data types or parse any string content. The function cell2mat concatenates the contents of a cell array into one array, i.e. it performs "un-nesting" of one cell array.
If you want to convert string data to numeric then you will need to use an appropriate function, e.g. str2double or sscanf or textscan or the like.
Respuesta aceptada
Walter Roberson
el 17 de Mzo. de 2021
T = [ {'0.115513'}
{'0.113281'}
{'0.112723'}
{'null' }
{'0.110491'}
{'0.107 ?'} ]
str2double(T)
will convert anything that does not look like a scalar number into NaN.
Más respuestas (0)
Ver también
Categorías
Más información sobre Data Type Conversion 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!