How to convert all the cell in a columns from char to string
80 ビュー (過去 30 日間)
古いコメントを表示
Marie-Claude Boisvert
2017 年 9 月 7 日
コメント済み: Marie-Claude Boisvert
2017 年 9 月 7 日
I have a table that contains char columns and double columns. I want to keep the same format but convert all the char into string to do some operation after.
'ABc' 'XYZ'
To : "ABC" "XYZ"
0 件のコメント
採用された回答
Guillaume
2017 年 9 月 7 日
Hum! it's not actually that easy as you can't use the syntax yourtable(:, somecolumns) to change the type of the column from cell array to string.
Option 1: use . indexing over the char columns
for columnname = yourcharcolumnnames %where yourcharcolumnnames is a cell array of the char column names
yourtable.(columnname{1}) = string(yourtable.(columnname{1}));
end
Option 2: create an auxiliary function for varfun that can take any column type
function column = convertcolumn(column)
if iscell(column) && ~isempty(column) && ischar(column)
column = string(column);
end
end
which you use with varfun:
newtable = varfun(@convertcolumn, yourtable);
その他の回答 (1 件)
Image Analyst
2017 年 9 月 7 日
This will do it:
% Set up
c = {'ABc'; 'XYZ'}
d = rand(2,1)
t = table(c, d, 'VariableNames', {'letters', 'numbers'})
% Now begin.
% First extract existing letters column of chars into a cell array.
cColumn = t{:, 'letters'}
% Convert char column to strings.
sColumn = string(cColumn)
% Make that into a table of strings with the same variable name, "strings"
st = table(sColumn, 'VariableNames', {'letters'})
% Delete existing char column.
t(:, 'letters') = []
% Add this column to the table in the same place as the char column was.
t = [st, t]
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Tables についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!