change table var type

66 次查看(过去 30 天)
LO
LO 2021-2-8
How can I change the variable type in a table from double to string ?
I found plenty of posts with the same issue but during import from excel. My table is already there and I need to change the var type of a column.
  2 个评论
KSSV
KSSV 2021-2-8
Read about num2str, sprintf.
LO
LO 2021-2-8
I resolved by creating a new 1column table of the right type and then concatenating it to the existing table (ugly but it works)

请先登录,再进行评论。

采纳的回答

Steven Lord
Steven Lord 2021-2-8
A = array2table(magic(4))
A = 4x4 table
Var1 Var2 Var3 Var4 ____ ____ ____ ____ 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1
A.Var1 = string(A.Var1)
A = 4x4 table
Var1 Var2 Var3 Var4 ____ ____ ____ ____ "16" 2 3 13 "5" 11 10 8 "9" 7 6 12 "4" 14 15 1
Though depending what you're trying to do, using discretize or categorical to create a categorical array might be a better option.
load patients
patients = table(LastName,Gender,Age,Height,Weight);
head(patients)
ans = 8x5 table
LastName Gender Age Height Weight ____________ __________ ___ ______ ______ {'Smith' } {'Male' } 38 71 176 {'Johnson' } {'Male' } 43 69 163 {'Williams'} {'Female'} 38 64 131 {'Jones' } {'Female'} 40 67 133 {'Brown' } {'Female'} 49 64 119 {'Davis' } {'Female'} 46 68 142 {'Miller' } {'Female'} 33 64 142 {'Wilson' } {'Male' } 40 68 180
patients.AgeCategory = discretize(patients.Age, 0:10:100, 'categorical');
patients.Gender = categorical(patients.Gender);
head(patients)
ans = 8x6 table
LastName Gender Age Height Weight AgeCategory ____________ ______ ___ ______ ______ ___________ {'Smith' } Male 38 71 176 [30, 40) {'Johnson' } Male 43 69 163 [40, 50) {'Williams'} Female 38 64 131 [30, 40) {'Jones' } Female 40 67 133 [40, 50) {'Brown' } Female 49 64 119 [40, 50) {'Davis' } Female 46 68 142 [40, 50) {'Miller' } Female 33 64 142 [30, 40) {'Wilson' } Male 40 68 180 [40, 50)

更多回答(1 个)

KALYAN ACHARJYA
KALYAN ACHARJYA 2021-2-8
编辑:KALYAN ACHARJYA 2021-2-8
"My table is already there and I need to change the var type of a column."
If the data is numeric, you can use num2str(variable_name) to convert numeric var to string data type.
Lets suppose you have table variable T and want to convert string of the particular column variable "col1", then
num2str(T.col1)
  2 个评论
LO
LO 2021-2-8
编辑:LO 2021-2-8
Thanks Kalyan, I am trying to input strings in a table column in a for loop cycle.
So the inputs are actually strings not numbers. when I try to put the strings into the table variable I just get NaNs (because the column type is double instead of string)
Jeremy Hughes
Jeremy Hughes 2021-2-8
I think you should share your code. Hard to tell what you really need to do.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by