Convert cell array with different datatypes to numeric

Hi everybody,
I am dealing with a cell array, where single numbers are saved as strings in the cells and some cells are empty. So cell2mat does not work. I want to convert the vector to double while keeping the numbers and replacing the empty cells with NaN.
What would be the fastest way to do this?
Best

 採用された回答

Stephen23
Stephen23 2015 年 3 月 11 日
編集済み: Stephen23 2015 年 3 月 11 日

0 投票

As you only have "single numbers" in the cells, then you can use str2double directly on the cell array:
>> A = {'123',[],'4','5678',[],'90'};
>> str2double(A)
ans = [123,NaN,4,5678,NaN,90]
The documentation states: "If str does not represent a valid scalar value, str2double returns NaN."

3 件のコメント

Christian F.
Christian F. 2015 年 3 月 11 日
Thanks, I get the following error using str2num:
Error using str2num (line 32) Requires string or character array input.
However, I dont know why...
Stephen23
Stephen23 2015 年 3 月 11 日
My answer uses str2double, not str2num.
Christian F.
Christian F. 2015 年 3 月 11 日
編集済み: Christian F. 2015 年 3 月 11 日
thanks, it works

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Type Conversion についてさらに検索

質問済み:

2015 年 3 月 11 日

編集済み:

2015 年 3 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by