我有一个带有列标题(字符串)和数据的csv文件。然后,我想添加一个具有特定标头'My new header'
的新列,并将数据存储在名为myNewData
的100x1双变量中。如何添加标题为'My new header'
的新列,列的值为myNewData
?
答案 0 :(得分:0)
您可以通过
实现这一目标importdata
您可以使用MATLAB文件交换中的this awesome function来编写数据,也可以通过fprintf
和dlmwrite
手动执行此操作
这是一个完整的例子:
% Write test data
filename = 'myfile01.csv';
fid = fopen(filename,'w');
fprintf(fid,'col1,col2,col3\n1,2,3\n4,5,6\n7,8,9\n10,11,12');
fclose(fid);
% Define new column
myNewHeader = 'My new header';
myNewData = randi(9,[4,1]);
% Read test data and headers
filename = 'myfile01.csv';
delimiter = ',';
headerlinesIn = 1;
A = importdata(filename, delimiter, headerlinesIn);
% Append new colum to data
data_new = cat(2, A.data, myNewData);
colheaders_new = [A.colheaders, myNewHeader];
clear A
% Write the result to a new file (or the same)
filename_new = 'myfile01_new.csv';
fid = fopen(filename_new,'w');
fprintf(fid, '%s,', colheaders_new{1,1:end-1});
fprintf(fid, '%s\n', colheaders_new{1,end});
fclose(fid);
dlmwrite(filename_new, data_new, '-append', 'precision', '%u', 'delimiter', ',');
% Or, using the function from the File Exchange:
csvwrite_with_headers(filename_new, data_new, colheaders_new);
答案 1 :(得分:0)
我能够使用Matlab中的表格在三行代码中完成此操作,如下所示:
table = readtable('myfile.csv','Delimiter',',');
table.class = newcol; %where class is the name of the header of the new column and newcol is a variable which has my new column data
writetable(table,'myfilenew.csv','Delimiter',',','QuoteStrings',false)