MATLAB Answers

change table var type

조회 수: 18(최근 30일)
LO
LO 2021년 2월 8일
댓글: Jeremy Hughes 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
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
Jeremy Hughes
Jeremy Hughes 2021년 2월 8일
I think you should share your code. Hard to tell what you really need to do.

댓글을 달려면 로그인하십시오.

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by