How to converting string values in a cell array to numbers when some strings are non-numeric (e.g. 'null')
조회 수: 47 (최근 30일)
이전 댓글 표시
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
Stephen23
2021년 3월 17일
"...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.
채택된 답변
Walter Roberson
2021년 3월 17일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!