How to write a table with mixed values?
5 次查看(过去 30 天)
显示 更早的评论
Hi All
how do I write a Table, that the first row is only string. in the next rows, the first column number, the second and third string, and the next ones number ?
0 个评论
采纳的回答
Walter Roberson
2020-4-20
You cannot do that with table() objects except by making everything string. You can define a Variable Description field for variables, but the description is only displayed if you use summarize(). table() objects are not designed for presentation purposes.
You also cannot do that with uitable() graphic objects except by making everything string. You can, though, define uitable ColumnName apart from the data values, which might be good enough for your purpose (do you just need the name displayed or do you need it to be stored with the table?)
9 个评论
Walter Roberson
2020-4-22
编辑:Walter Roberson
2020-4-22
%we need some example data for the purpose of illustration. Do not include
%this in your real program
col1 = randi(9,[5,1]);
col2 = {'hello'; 'how'; 'are'; 'you'; 'today'};
col3 = {'My'; 'favorite'; 'color'; 'is'; 'pizza!'};
col4 = -randi(9,[5 1]);
col5 = randi(9,[5 1]).^2;
%table_without_header is standing in for your existing table before the first
%row has been added. Use your own table instead!
table_without_header = table(col1,col2,col3,col4,col5);
%and this is the cell of strings to put on the column. Use your own
header = {'Quantity', 'Category', 'Description', 'Selling Price', 'Number Sold'};
%now we go to work. This part you copy, changing variable names as needed
Tc = [header; table2cell(table_without_header)];
table_with_header = cell2table(Tc, 'VariableNames', table_without_header.Properties.VariableNames);
%we now have a table like you described, with the first row being string,
%and otherwise the first column being numeric, and the second and third
%columns being string, and the remaining columns being numeric
%now that we have it, write it out
writetable(table_with_header, 'FileNameToWriteTo.xlsx');
Note: You might want to use
'writevariablenames', false
Also, be sure to delete the output file FileNameToWriteTo.xlsx before you run the test.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!