How to converting string values in a cell array to numbers when some strings are non-numeric (e.g. 'null')

54 visualizzazioni (ultimi 30 giorni)
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 Commenti
Stephen23
Stephen23 il 17 Mar 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.

Accedi per commentare.

Risposta accettata

Walter Roberson
Walter Roberson il 17 Mar 2021
T = [ {'0.115513'}
{'0.113281'}
{'0.112723'}
{'null' }
{'0.110491'}
{'0.107 ?'} ]
T = 6×1 cell array
{'0.115513'} {'0.113281'} {'0.112723'} {'null' } {'0.110491'} {'0.107 ?' }
str2double(T)
ans = 6×1
0.1155 0.1133 0.1127 NaN 0.1105 NaN
will convert anything that does not look like a scalar number into NaN.

Più risposte (0)

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by