Converting Strings in a Cell Array to Doubles (trickier than you think)
25 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Darien Niamir
am 26 Mai 2017
Kommentiert: Jan
am 26 Mai 2017
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 Kommentar
Jan
am 26 Mai 2017
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?
Akzeptierte Antwort
Guillaume
am 26 Mai 2017
"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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!