Eka
Eka

Reputation: 15002

How to save data to a txt file or excel file in MATLAB

How to save this data (i and a) to a .txt file or .xls file in MATLAB?

for i=1:10
   i
   a=i*2
end

Upvotes: 2

Views: 15568

Answers (3)

angainor
angainor

Reputation: 11810

Use csvwrite to write coma separated values to a text file. You can read it in Excel, and it is a text file at the same time

i=1:10;
a=i*2;
csvwrite('data.csv', [i; a]);

Upvotes: 4

Gunther Struyf
Gunther Struyf

Reputation: 11168

To save to a text file, there is fprintf, example (from documentation):

x = 0:.1:1;
A = [x; exp(x)];

fileID = fopen('exp.txt','w');
fprintf(fileID,'%6s %12s\n','x','exp(x)');
fprintf(fileID,'%6.2f %12.8f\n',A);
fclose(fileID);

To save to an excel file, there is xlswrite, example (from documentation):

filename = 'testdata.xlsx';
A = [12.7, 5.02, -98, 63.9, 0, -.2, 56];
xlswrite(filename,A)

If you do not have excel installed, this will not work. An alternative is then csvwrite, which you later on can easily import in excel (on another pc eg).

Upvotes: 2

Genís
Genís

Reputation: 1508

Matlab provides an file I/O interface similar to that of C: you open a file, output data or formatted text, and close it:

f = fopen( "file.txt", "w" );
for i=1:10,
  a=i*2
  fprintf( f, "%d ", a );
end
fclose( f );  

Upvotes: 2

Related Questions