Converting Strings in a Cell Array to Doubles (trickier than you think)

25 ビュー (過去 30 日間)
Darien Niamir
Darien Niamir 2017 年 5 月 26 日
コメント済み: Jan 2017 年 5 月 26 日
Hello,
I have a very large cell array full of strings. Most of these cells contain strings that are really doubles in string format. Some are just pure strings. Some cells are also strings that are combinations of strings and doubles in string format. There are also some cells that are empty.
I would like to convert this cell array into another cell array that is exactly the same, except all the cells that were purely doubles in string format are now doubles NOT in string format.
I have one solution, which is: Data_Out= cellfun(@(x)str2double(x), Data_In);
However, this solution is very time taxing. I would prefer a more simple solution.
I've also tried playing around with the "isstrprop" function but have not found a solution using this yet.
Any help would be greatly appreciated.
  1 件のコメント
Jan
Jan 2017 年 5 月 26 日
An explicite example of the cell would be useful. How do you want to treat "1e4", "Inf" and "NaN"? How is a "pure string" or "pure number" identified reliably?

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

採用された回答

Guillaume
Guillaume 2017 年 5 月 26 日
"I have one solution, which is: Data_Out= cellfun(@(x)str2double(x), Data_In);"
Considering that your anonymous function just pass the input straight to str2double, it's not needed:
Data_Out = cellfun(@str2double, Data_In);
would be slightly faster as you're losing the cost of an anonymous function call.
But in any case, str2double is perfectly happy with a cell array input, so the cellfun is not even necessary:
Data_Out = str2double(Data_In);
"However, this solution is very time taxing. I would prefer a more simple solution"
Not having the pointless cellfun should speed it up a bit, but this is already the simplest solution. Parsing strings into numbers is a time consuming process. I really doubt that you're going to find any faster algorithm.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by