Reputation: 27
If you have a table class "T"
T =
Var1 Var2 Var3 Var4
____ ________ ____ _____
M 45 45 'NY' true
F 41 32 'CA' false
M 40 34 'MA' false
And you want to write the values in a file you could use, for instance:
writetable(T,'myData.txt','Delimiter', ...)
But this will delete all the information you had in myData.txt . I was wondering if there is an append function for table, or some way write without remove the old content of myData.txt.
So, Image:
type myData.txt
Hello
writetable(T, ...)
type myData.txt
Hello
Var1 Var2 Var3 Var4
M 45 45 'NY' true
F 41 32 'CA' false
M 40 34 'MA' false
Upvotes: 2
Views: 7441
Reputation: 128
Bob's answer is perfect for small tables. For large tables, to avoid the for loop, I recommend writing the second table to a second file, and then you can merge the files. Here is code for that:
writetable(T1,'data_01.csv');
writetable(T2,'data_02.csv','WriteVariableNames',false);
you don't want to have the variable names on the second file so that you can merge the files perfectly to a new file. If you are on Linux you can simply do:
cat data_*.csv >> data.csv
And, yet if the tables are very big, I would recommend using 'datastore'. Here is a code for that:
writetable(T1,'data_01.csv');
writetable(T2,'data_02.csv');
here we should keep the variableNames in the second file as well, so the datastore function can read the files properly:
ds = datastore('data_*.csv');
then, you can read slice by slice using 'read' function or read completely using 'readall' function, depending on your need. Please, check the documentations for that.
Upvotes: 2
Reputation: 459
One way is to write to the file using fopen(). Create the table:
LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
Age = [38;43;38;40;49];
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
T = table(LastName,Age,Height,Weight)
Write the file:
writetable(T,'table.csv')
Open the file again:
fid = fopen('table.csv','a')
Write out the table a second time:
fmt = varfun(@(x) class(x),T,'OutputFormat','cell');
fmt(strcmp(fmt,'double'))={'%g'};
fmt(strcmp(fmt,'cell'))={'%s'};
fmt=[strjoin(fmt,',') '\n']
for r=1:size(T,1)
x=table2cell(T(r,:));
fprintf(fid,fmt,x{:});
end
fclose(fid);
Upvotes: 2