how to keep index using writable in matlab

When using the writetable function in MATLAB to write data to a file, you can specify if you want to include row and/or column names using the 'WriteRowNames' and 'WriteVariableNames' options, respectively.

If you want to keep the row index as a separate column in the output file, you'll need to add a new column to your table before writing it using writetable. Here's an example code that adds an index column to a table before writing it using writetable:

main.m
% create sample table
data = {'John'; 'Jane'; 'Bob'};
tbl = table(data);

% add index column
nRows = size(tbl, 1);
idx = (1:nRows)';
tbl.idx = idx;

% write table to file with index column included
writetable(tbl, 'output.csv', 'WriteRowNames', true, 'WriteVariableNames', true)
279 chars
12 lines

This will create a CSV file with the following content:

|idx|Var1 | |---|-----| |1 |John | |2 |Jane | |3 |Bob |

As you can see, the row index has been added as a separate column, with 'idx' as the column name.

related categories

gistlibby LogSnag