2

Output of my matlab code gives out a string each time it is executed. I need to save the string in a excel sheet each time without overwriting the previous data in the excel sheet. The new string must be added in a new cell in the excel sheet.

Anurag
  • 21
  • 2
  • You need use 'writematrix' or 'writecell' Matlab functions: https://www.mathworks.com/help/matlab/import_export/exporting-to-excel-spreadsheets.html – geoinformatic Jan 04 '20 at 09:19

3 Answers3

1

The writecell function has an optional range parameter, which allows you to write a certain range, without touching the rest of the sheet.

writecell({'A' 'B' 'C'},'C.xls','Range','A1:C1')

In case you want to write numeric data instead of strings, writematrix is preferable.

Daniel
  • 36,610
  • 3
  • 36
  • 69
1

The example:

filename = 'testdata.xlsx';
for i = 1:10
textdata = {['some text ', num2str(i)]};
writecell(textdata,filename,'Sheet',1,'Range',['B',num2str(i)]);
end

enter image description here

  • in this code all the 10 output strings are generated at a time. i need to save the strings after each time my code is executed. – Anurag Jan 04 '20 at 09:42
  • In this code each string is generated iteratively. Just insert your code instead 'textdata = {['some text ', num2str(i)]}' – geoinformatic Jan 04 '20 at 09:54
1

Daniels approach works with writecell, writetable, and writematrix, you just need to keep track of the range (or update the row indices of your range...)

There is a more complicated (or sophisticated) approach described here or here.

The question is if you

  1. really need to write there to the excel file consistently, or if your RAM allows to store everything in a matlab-table and write it once at the end to a file
  2. does it have to be an excel file, or is a .mat-file OK? (Which is easier to update)
  3. if you want to write to a comma-separated file, can you write to a .csv file? You can append a string (that can be a formatted line) to a text file, see here.

Option 3 is probably all you need if you don't want to change your original code.

dlmwrite('test.csv',MATRIX,'delimiter',',','-append');
max
  • 3,915
  • 2
  • 9
  • 25