Effacer les filtres
Effacer les filtres

Convert multiple strings in a table to numbers

101 vues (au cours des 30 derniers jours)
YaaW
YaaW le 12 Jan 2023
Commenté : YaaW le 12 Jan 2023
I'm trying to convert multiple strings in a table to numbers, but I keep on getting an error (either 'NaN' as an answer, or "Right hand side of an assignment into a table must be another table or a cell array").
It's a table where columns 13:68 contain either a "number" or "" (empty cell), and I want the string numbers to be converted to a number, and the empty cells to a NaN.
It works if I try this for one column only, using:
Table.X = str2double(Table.X);
But I have to do this for 56 columns and there must be a way to do it quicker than for each of them separately, however trying:
Table.(: ,X:YY) = str2double(Table.(: ,X:YY));
doesn't seem to work, as it returns an error, and changing the () to {} returns a NaN.
Anybody that knows how I can easily change string to double for multiple columns in a table?

Réponse acceptée

Stephen23
Stephen23 le 12 Jan 2023
T = cell2table({"cat","1.2","","3.4";"in","4.5","6","7";"hat","","89",""})
T = 3×4 table
Var1 Var2 Var3 Var4 _____ _____ ____ _____ "cat" "1.2" "" "3.4" "in" "4.5" "6" "7" "hat" "" "89" ""
T = convertvars(T,2:4,'double')
T = 3×4 table
Var1 Var2 Var3 Var4 _____ ____ ____ ____ "cat" 1.2 NaN 3.4 "in" 4.5 6 7 "hat" NaN 89 NaN
  1 commentaire
YaaW
YaaW le 12 Jan 2023
It works, thanks so much!!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by