How to put string to a column of a table

155 ビュー (過去 30 日間)
Saugata Bose
Saugata Bose 2020 年 7 月 7 日
編集済み: Adam Danz 2020 年 7 月 13 日
Hi,
It may sound silly, but I cant figure out how to insert a string to a column of a table.
I have tried few ways to insert, but failed.
The thing is, I need to insert a string, suppose, "cricketer" in the column, named "Role" in the table, called, "Players".
The table is of form like this:
Name Role
"abc"
"bcd"
"cdf"
I have tried few things randomly, like
Players.Role(:,1)="cricketer"
but it appears NaN in the cells of the Role column.
Can you please show me the right way to do it?
thanks,

回答 (1 件)

Adam Danz
Adam Danz 2020 年 7 月 7 日
編集済み: Adam Danz 2020 年 7 月 13 日
"... but it appears NaN in the cells of the Role column."
Sounds like the Role column is an empty cell array or a numeric column. Table columns but contain the same type of data and cannot contain mixed classes. You can use a cell array to enter mixed data types if needed.
Players = table(["abc";"dcd";"cdf"], cell(3,1),'VariableNames',{'Name','Role'})
Players.Role{1} = 'Cricketer';
If the entire column should be strings, you can convert the cell array to a string array,
Players.Role = repmat("Cricketer", size(Players.Name))
or you can set the initial values of "Role" as a string array rather than a cell array,
Players = table(["abc";"dcd";"cdf"], ["";"";""],'VariableNames',{'Name','Role'})
Players.Role(:) = "Cricketer";

Community Treasure Hunt

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

Start Hunting!

Translated by