Reputation: 1661
I am performing a simulation many many times, and would like to store the result in a csv file.
I could just save the results in an array and write the array to a csv, but the array would be very large and a big strain on my system.
I was thinking it could be easier to simulate, save the result of one simulation in a csv, complete a new simulation, and then store the new result in the second line of the csv.
How can I write csv lines one by one in matlab?
Upvotes: 1
Views: 3314
Reputation: 41
Easy, use: dlmwrite(filename,M,'-append')
For example:
simulation_results = [1,2,3,4]
dlmwrite('C:\<Your Directory Path>\simulaton_results.csv', simulation_results, '-append');
This will append the simulation_results matrix to the end of the file you specify. The default delimiter is a comma ... perfect for writing csv files.
Upvotes: 4
Reputation: 173
Try fprintf
%save to file
%save using fprintf function
fid_out = fopen('file_out.csv','w'); %open file and create fid
%save tab-separated column headers
%define column format and names and save to file
fprintf(fid_out,'%s\t%s\t%s\t%s\n','a_name','b_name','c_name','d_name');
%save tab-separated columns of data
for i = 1:size(data,1) %loop trough each line of each data variable and save to file line by line
%define column format and date to be saved.
%use () for numeric data, and {} for strings
fprintf(fid_out,'%s\t%s\t%d\t%.5f\n',a{i},b{i},c(i),d(i));
end
fclose(fid_out); %close file
%NOTE: fprintf cannot save structured data
Upvotes: 1